diff --git a/tasks/0000_369_369503_qa_1/environment/Dockerfile b/tasks/0000_369_369503_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0000_369_369503_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0000_369_369503_qa_1/environment/pull_bucket.py b/tasks/0000_369_369503_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0000_369_369503_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/0000_369_369503_qa_1/tests/__pycache__/grader.cpython-312.pyc b/tasks/0000_369_369503_qa_1/tests/__pycache__/grader.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..79f2db873c776944fcde5c303550001fa58b52ba Binary files /dev/null and b/tasks/0000_369_369503_qa_1/tests/__pycache__/grader.cpython-312.pyc differ diff --git a/tasks/0000_369_369503_qa_1/tests/grader.py b/tasks/0000_369_369503_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0000_369_369503_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/0000_369_369503_qa_1/tests/test.sh b/tasks/0000_369_369503_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0000_369_369503_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/0001_085_1085629_qa_4/tests/grader.py b/tasks/0001_085_1085629_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_085_1085629_qa_4/tests/grader.py +++ b/tasks/0001_085_1085629_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_231_1231918_qa_1/tests/grader.py b/tasks/0001_231_1231918_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_231_1231918_qa_1/tests/grader.py +++ b/tasks/0001_231_1231918_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_257_1257061_qa_1/tests/grader.py b/tasks/0001_257_1257061_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_257_1257061_qa_1/tests/grader.py +++ b/tasks/0001_257_1257061_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_323_1323152_qa_1/tests/grader.py b/tasks/0001_323_1323152_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_323_1323152_qa_1/tests/grader.py +++ b/tasks/0001_323_1323152_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_426_1426219_qa_2/tests/grader.py b/tasks/0001_426_1426219_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_426_1426219_qa_2/tests/grader.py +++ b/tasks/0001_426_1426219_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0001_464_1464229_qa_3/tests/grader.py b/tasks/0001_464_1464229_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_464_1464229_qa_3/tests/grader.py +++ b/tasks/0001_464_1464229_qa_3/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0001_464_1464229_qa_4/tests/grader.py b/tasks/0001_464_1464229_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_464_1464229_qa_4/tests/grader.py +++ b/tasks/0001_464_1464229_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0001_532_1532154_qa_3/tests/grader.py b/tasks/0001_532_1532154_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_532_1532154_qa_3/tests/grader.py +++ b/tasks/0001_532_1532154_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_532_1532154_qa_4/environment/Dockerfile b/tasks/0001_532_1532154_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_532_1532154_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_532_1532154_qa_4/environment/pull_bucket.py b/tasks/0001_532_1532154_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_532_1532154_qa_4/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0001_532_1532154_qa_4/tests/grader.py b/tasks/0001_532_1532154_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0001_532_1532154_qa_4/tests/grader.py @@ -0,0 +1,172 @@ +"""Deterministic short-answer grader v2 — NO LLM judge. + +Tiers (all offline/deterministic): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) +""" +from __future__ import annotations +import os, re, sys +from dataclasses import dataclass + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + + +@dataclass +class GradeResult: + reward: float + method: str + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str): + if not s: + return None + m = _NUMERIC_RE.search(str(s).replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol + + +def _is_clean_number(s: str) -> bool: + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False + + +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # Tier 1: exact + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if _num_close(g, c, abs_tol, rel_tol): + return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") + + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls(): + try: + with open("/workdir/.n_tool_calls") as fh: + return int(fh.read().strip()) + except (OSError, ValueError): + pass + raw = os.environ.get("N_TOOL_CALLS") + if raw is not None: + try: + return int(str(raw).strip()) + except ValueError: + return None + return None + + +def _tool_efficiency(n): + if n is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n / budget)) + + +def _tols(): + def _f(name): + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +def main_json() -> int: + import json + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + return 0 + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0001_532_1532154_qa_4/tests/test.sh b/tasks/0001_532_1532154_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_532_1532154_qa_4/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0001_660_1660748_qa_2/tests/grader.py b/tasks/0001_660_1660748_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_660_1660748_qa_2/tests/grader.py +++ b/tasks/0001_660_1660748_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0001_660_1660748_qa_5/tests/grader.py b/tasks/0001_660_1660748_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_660_1660748_qa_5/tests/grader.py +++ b/tasks/0001_660_1660748_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_692_1692435_qa_3/environment/Dockerfile b/tasks/0001_692_1692435_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_692_1692435_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_692_1692435_qa_3/environment/pull_bucket.py b/tasks/0001_692_1692435_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_692_1692435_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_692_1692435_qa_3/tests/grader.py b/tasks/0001_692_1692435_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0001_692_1692435_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_692_1692435_qa_3/tests/test.sh b/tasks/0001_692_1692435_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_692_1692435_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_692_1692435_qa_4/tests/grader.py b/tasks/0001_692_1692435_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_692_1692435_qa_4/tests/grader.py +++ b/tasks/0001_692_1692435_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_725_1725548_qa_1/tests/grader.py b/tasks/0001_725_1725548_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_725_1725548_qa_1/tests/grader.py +++ b/tasks/0001_725_1725548_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_754_1754320_qa_2/tests/grader.py b/tasks/0001_754_1754320_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_754_1754320_qa_2/tests/grader.py +++ b/tasks/0001_754_1754320_qa_2/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0001_755_1755036_qa_1/environment/Dockerfile b/tasks/0001_755_1755036_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_755_1755036_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_755_1755036_qa_1/environment/pull_bucket.py b/tasks/0001_755_1755036_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_755_1755036_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/0001_755_1755036_qa_1/tests/grader.py b/tasks/0001_755_1755036_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0001_755_1755036_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/0001_755_1755036_qa_1/tests/test.sh b/tasks/0001_755_1755036_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_755_1755036_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/0001_825_1825877_qa_5/tests/grader.py b/tasks/0001_825_1825877_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_825_1825877_qa_5/tests/grader.py +++ b/tasks/0001_825_1825877_qa_5/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0001_892_1892776_qa_1/tests/grader.py b/tasks/0001_892_1892776_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_892_1892776_qa_1/tests/grader.py +++ b/tasks/0001_892_1892776_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_893_1893246_qa_3/tests/grader.py b/tasks/0001_893_1893246_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_893_1893246_qa_3/tests/grader.py +++ b/tasks/0001_893_1893246_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_897_1897174_qa_5/tests/grader.py b/tasks/0001_897_1897174_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_897_1897174_qa_5/tests/grader.py +++ b/tasks/0001_897_1897174_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_902_1902890_qa_5/tests/grader.py b/tasks/0001_902_1902890_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_902_1902890_qa_5/tests/grader.py +++ b/tasks/0001_902_1902890_qa_5/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0001_930_1930899_qa_1/tests/grader.py b/tasks/0001_930_1930899_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_930_1930899_qa_1/tests/grader.py +++ b/tasks/0001_930_1930899_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_081_2081941_qa_4/tests/grader.py b/tasks/0002_081_2081941_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0002_081_2081941_qa_4/tests/grader.py +++ b/tasks/0002_081_2081941_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0002_253_2253838_qa_5/tests/grader.py b/tasks/0002_253_2253838_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0002_253_2253838_qa_5/tests/grader.py +++ b/tasks/0002_253_2253838_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/0011_355_11355842_qa_3/tests/grader.py b/tasks/0011_355_11355842_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0011_355_11355842_qa_3/tests/grader.py +++ b/tasks/0011_355_11355842_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/0011_355_11355842_qa_4/tests/grader.py b/tasks/0011_355_11355842_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0011_355_11355842_qa_4/tests/grader.py +++ b/tasks/0011_355_11355842_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0011_998_11998157_qa_5/tests/grader.py b/tasks/0011_998_11998157_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0011_998_11998157_qa_5/tests/grader.py +++ b/tasks/0011_998_11998157_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/0012_179_12179865_qa_4/environment/Dockerfile b/tasks/0012_179_12179865_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0012_179_12179865_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0012_179_12179865_qa_4/environment/pull_bucket.py b/tasks/0012_179_12179865_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0012_179_12179865_qa_4/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0012_179_12179865_qa_4/tests/grader.py b/tasks/0012_179_12179865_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0012_179_12179865_qa_4/tests/grader.py @@ -0,0 +1,172 @@ +"""Deterministic short-answer grader v2 — NO LLM judge. + +Tiers (all offline/deterministic): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) +""" +from __future__ import annotations +import os, re, sys +from dataclasses import dataclass + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + + +@dataclass +class GradeResult: + reward: float + method: str + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str): + if not s: + return None + m = _NUMERIC_RE.search(str(s).replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol + + +def _is_clean_number(s: str) -> bool: + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False + + +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # Tier 1: exact + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if _num_close(g, c, abs_tol, rel_tol): + return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") + + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls(): + try: + with open("/workdir/.n_tool_calls") as fh: + return int(fh.read().strip()) + except (OSError, ValueError): + pass + raw = os.environ.get("N_TOOL_CALLS") + if raw is not None: + try: + return int(str(raw).strip()) + except ValueError: + return None + return None + + +def _tool_efficiency(n): + if n is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n / budget)) + + +def _tols(): + def _f(name): + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +def main_json() -> int: + import json + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + return 0 + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0012_179_12179865_qa_4/tests/test.sh b/tasks/0012_179_12179865_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0012_179_12179865_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/0014_164_14164509_qa_1/tests/grader.py b/tasks/0014_164_14164509_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0014_164_14164509_qa_1/tests/grader.py +++ b/tasks/0014_164_14164509_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/0015_861_15861774_qa_1/tests/grader.py b/tasks/0015_861_15861774_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0015_861_15861774_qa_1/tests/grader.py +++ b/tasks/0015_861_15861774_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0018_563_18563893_qa_5/tests/grader.py b/tasks/0018_563_18563893_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0018_563_18563893_qa_5/tests/grader.py +++ b/tasks/0018_563_18563893_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/0019_288_19288397_qa_1/tests/grader.py b/tasks/0019_288_19288397_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0019_288_19288397_qa_1/tests/grader.py +++ b/tasks/0019_288_19288397_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/0019_434_19434702_qa_1/tests/grader.py b/tasks/0019_434_19434702_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0019_434_19434702_qa_1/tests/grader.py +++ b/tasks/0019_434_19434702_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/0019_685_19685428_qa_1/tests/grader.py b/tasks/0019_685_19685428_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0019_685_19685428_qa_1/tests/grader.py +++ b/tasks/0019_685_19685428_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/0020_764_20764174_qa_3/tests/grader.py b/tasks/0020_764_20764174_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0020_764_20764174_qa_3/tests/grader.py +++ b/tasks/0020_764_20764174_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/0020_828_20828784_qa_1/tests/grader.py b/tasks/0020_828_20828784_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0020_828_20828784_qa_1/tests/grader.py +++ b/tasks/0020_828_20828784_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_3/environment/Dockerfile b/tasks/0021_193_21193214_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0021_193_21193214_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0021_193_21193214_qa_3/environment/pull_bucket.py b/tasks/0021_193_21193214_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0021_193_21193214_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/0021_193_21193214_qa_3/tests/grader.py b/tasks/0021_193_21193214_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0021_193_21193214_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/0021_193_21193214_qa_3/tests/test.sh b/tasks/0021_193_21193214_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0021_193_21193214_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/0022_258_22258436_qa_1/tests/grader.py b/tasks/0022_258_22258436_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0022_258_22258436_qa_1/tests/grader.py +++ b/tasks/0022_258_22258436_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_457_22457642_qa_2/tests/grader.py b/tasks/0022_457_22457642_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0022_457_22457642_qa_2/tests/grader.py +++ b/tasks/0022_457_22457642_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/0022_457_22457642_qa_5/tests/grader.py b/tasks/0022_457_22457642_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0022_457_22457642_qa_5/tests/grader.py +++ b/tasks/0022_457_22457642_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/0022_482_22482992_qa_2/environment/Dockerfile b/tasks/0022_482_22482992_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0022_482_22482992_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0022_482_22482992_qa_2/environment/pull_bucket.py b/tasks/0022_482_22482992_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0022_482_22482992_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/0022_482_22482992_qa_2/tests/grader.py b/tasks/0022_482_22482992_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0022_482_22482992_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/0022_482_22482992_qa_2/tests/test.sh b/tasks/0022_482_22482992_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0022_482_22482992_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/0022_712_22712745_qa_5/tests/grader.py b/tasks/0022_712_22712745_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0022_712_22712745_qa_5/tests/grader.py +++ b/tasks/0022_712_22712745_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/0024_028_24028302_qa_2/tests/grader.py b/tasks/0024_028_24028302_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0024_028_24028302_qa_2/tests/grader.py +++ b/tasks/0024_028_24028302_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/0024_654_24654257_qa_3/tests/grader.py b/tasks/0024_654_24654257_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0024_654_24654257_qa_3/tests/grader.py +++ b/tasks/0024_654_24654257_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_658_24658460_qa_4/tests/grader.py b/tasks/0024_658_24658460_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0024_658_24658460_qa_4/tests/grader.py +++ b/tasks/0024_658_24658460_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/0024_893_24893903_qa_5/tests/grader.py b/tasks/0024_893_24893903_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0024_893_24893903_qa_5/tests/grader.py +++ b/tasks/0024_893_24893903_qa_5/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0028_198_28198239_qa_1/tests/grader.py b/tasks/0028_198_28198239_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0028_198_28198239_qa_1/tests/grader.py +++ b/tasks/0028_198_28198239_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/0028_521_28521768_qa_3/tests/grader.py b/tasks/0028_521_28521768_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0028_521_28521768_qa_3/tests/grader.py +++ b/tasks/0028_521_28521768_qa_3/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0030_991_30991339_qa_2/tests/grader.py b/tasks/0030_991_30991339_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0030_991_30991339_qa_2/tests/grader.py +++ b/tasks/0030_991_30991339_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0031_374_31374028_qa_4/tests/grader.py b/tasks/0031_374_31374028_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0031_374_31374028_qa_4/tests/grader.py +++ b/tasks/0031_374_31374028_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/0031_927_31927038_qa_5/tests/grader.py b/tasks/0031_927_31927038_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0031_927_31927038_qa_5/tests/grader.py +++ b/tasks/0031_927_31927038_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/0032_614_32614408_qa_1/tests/grader.py b/tasks/0032_614_32614408_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0032_614_32614408_qa_1/tests/grader.py +++ b/tasks/0032_614_32614408_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0032_631_32631784_qa_4/tests/grader.py b/tasks/0032_631_32631784_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0032_631_32631784_qa_4/tests/grader.py +++ b/tasks/0032_631_32631784_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0032_734_32734784_qa_3/tests/grader.py b/tasks/0032_734_32734784_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0032_734_32734784_qa_3/tests/grader.py +++ b/tasks/0032_734_32734784_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_273_33273125_qa_3/tests/grader.py b/tasks/0033_273_33273125_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0033_273_33273125_qa_3/tests/grader.py +++ b/tasks/0033_273_33273125_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_290_33290847_qa_1/tests/grader.py b/tasks/0033_290_33290847_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0033_290_33290847_qa_1/tests/grader.py +++ b/tasks/0033_290_33290847_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0033_589_33589892_qa_1/tests/grader.py b/tasks/0033_589_33589892_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0033_589_33589892_qa_1/tests/grader.py +++ b/tasks/0033_589_33589892_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0034_886_34886359_qa_5/environment/Dockerfile b/tasks/0034_886_34886359_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0034_886_34886359_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0034_886_34886359_qa_5/environment/pull_bucket.py b/tasks/0034_886_34886359_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0034_886_34886359_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/0034_886_34886359_qa_5/tests/grader.py b/tasks/0034_886_34886359_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0034_886_34886359_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/0034_886_34886359_qa_5/tests/test.sh b/tasks/0034_886_34886359_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0034_886_34886359_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/0035_225_35225660_qa_3/tests/grader.py b/tasks/0035_225_35225660_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0035_225_35225660_qa_3/tests/grader.py +++ b/tasks/0035_225_35225660_qa_3/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0035_236_35236430_qa_3/tests/grader.py b/tasks/0035_236_35236430_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0035_236_35236430_qa_3/tests/grader.py +++ b/tasks/0035_236_35236430_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0035_303_35303628_qa_2/tests/grader.py b/tasks/0035_303_35303628_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0035_303_35303628_qa_2/tests/grader.py +++ b/tasks/0035_303_35303628_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/0035_638_35638998_qa_4/tests/grader.py b/tasks/0035_638_35638998_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0035_638_35638998_qa_4/tests/grader.py +++ b/tasks/0035_638_35638998_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/0035_645_35645519_qa_5/tests/grader.py b/tasks/0035_645_35645519_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0035_645_35645519_qa_5/tests/grader.py +++ b/tasks/0035_645_35645519_qa_5/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0035_921_35921172_qa_5/tests/grader.py b/tasks/0035_921_35921172_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0035_921_35921172_qa_5/tests/grader.py +++ b/tasks/0035_921_35921172_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/0038_159_38159473_qa_2/tests/grader.py b/tasks/0038_159_38159473_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0038_159_38159473_qa_2/tests/grader.py +++ b/tasks/0038_159_38159473_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/0038_408_38408993_qa_2/tests/grader.py b/tasks/0038_408_38408993_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0038_408_38408993_qa_2/tests/grader.py +++ b/tasks/0038_408_38408993_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/0038_412_38412209_qa_3/tests/grader.py b/tasks/0038_412_38412209_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0038_412_38412209_qa_3/tests/grader.py +++ b/tasks/0038_412_38412209_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/0038_606_38606903_qa_3/tests/grader.py b/tasks/0038_606_38606903_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0038_606_38606903_qa_3/tests/grader.py +++ b/tasks/0038_606_38606903_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/0038_672_38672361_qa_4/tests/grader.py b/tasks/0038_672_38672361_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0038_672_38672361_qa_4/tests/grader.py +++ b/tasks/0038_672_38672361_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0038_949_38949847_qa_2/tests/grader.py b/tasks/0038_949_38949847_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0038_949_38949847_qa_2/tests/grader.py +++ b/tasks/0038_949_38949847_qa_2/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0039_354_39354291_qa_3/tests/grader.py b/tasks/0039_354_39354291_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0039_354_39354291_qa_3/tests/grader.py +++ b/tasks/0039_354_39354291_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0039_714_39714962_qa_3/environment/Dockerfile b/tasks/0039_714_39714962_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0039_714_39714962_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0039_714_39714962_qa_3/environment/pull_bucket.py b/tasks/0039_714_39714962_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0039_714_39714962_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/0039_714_39714962_qa_3/tests/grader.py b/tasks/0039_714_39714962_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0039_714_39714962_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/0039_714_39714962_qa_3/tests/test.sh b/tasks/0039_714_39714962_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0039_714_39714962_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/0039_968_39968264_qa_3/tests/grader.py b/tasks/0039_968_39968264_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0039_968_39968264_qa_3/tests/grader.py +++ b/tasks/0039_968_39968264_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0040_340_40340401_qa_2/tests/grader.py b/tasks/0040_340_40340401_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0040_340_40340401_qa_2/tests/grader.py +++ b/tasks/0040_340_40340401_qa_2/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0040_620_40620313_qa_5/tests/grader.py b/tasks/0040_620_40620313_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0040_620_40620313_qa_5/tests/grader.py +++ b/tasks/0040_620_40620313_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/0040_673_40673055_qa_4/environment/Dockerfile b/tasks/0040_673_40673055_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0040_673_40673055_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0040_673_40673055_qa_4/environment/pull_bucket.py b/tasks/0040_673_40673055_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0040_673_40673055_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/0040_673_40673055_qa_4/tests/grader.py b/tasks/0040_673_40673055_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0040_673_40673055_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/0040_673_40673055_qa_4/tests/test.sh b/tasks/0040_673_40673055_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0040_673_40673055_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/0040_983_40983485_qa_1/tests/grader.py b/tasks/0040_983_40983485_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0040_983_40983485_qa_1/tests/grader.py +++ b/tasks/0040_983_40983485_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/0041_018_41018707_qa_4/environment/Dockerfile b/tasks/0041_018_41018707_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0041_018_41018707_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0041_018_41018707_qa_4/environment/pull_bucket.py b/tasks/0041_018_41018707_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0041_018_41018707_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/0041_018_41018707_qa_4/tests/grader.py b/tasks/0041_018_41018707_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0041_018_41018707_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/0041_018_41018707_qa_4/tests/test.sh b/tasks/0041_018_41018707_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0041_018_41018707_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/0041_604_41604680_qa_3/tests/grader.py b/tasks/0041_604_41604680_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0041_604_41604680_qa_3/tests/grader.py +++ b/tasks/0041_604_41604680_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_604_41604696_qa_3/environment/Dockerfile b/tasks/0041_604_41604696_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0041_604_41604696_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0041_604_41604696_qa_3/environment/pull_bucket.py b/tasks/0041_604_41604696_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0041_604_41604696_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/0041_604_41604696_qa_3/tests/grader.py b/tasks/0041_604_41604696_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0041_604_41604696_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/0041_604_41604696_qa_3/tests/test.sh b/tasks/0041_604_41604696_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0041_604_41604696_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/0041_658_41658396_qa_4/tests/grader.py b/tasks/0041_658_41658396_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0041_658_41658396_qa_4/tests/grader.py +++ b/tasks/0041_658_41658396_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0042_488_42488426_qa_1/tests/grader.py b/tasks/0042_488_42488426_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0042_488_42488426_qa_1/tests/grader.py +++ b/tasks/0042_488_42488426_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/0043_510_43510597_qa_3/tests/grader.py b/tasks/0043_510_43510597_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0043_510_43510597_qa_3/tests/grader.py +++ b/tasks/0043_510_43510597_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/0043_512_43512681_qa_2/environment/Dockerfile b/tasks/0043_512_43512681_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0043_512_43512681_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0043_512_43512681_qa_2/environment/pull_bucket.py b/tasks/0043_512_43512681_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0043_512_43512681_qa_2/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0043_512_43512681_qa_2/tests/grader.py b/tasks/0043_512_43512681_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0043_512_43512681_qa_2/tests/grader.py @@ -0,0 +1,172 @@ +"""Deterministic short-answer grader v2 — NO LLM judge. + +Tiers (all offline/deterministic): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) +""" +from __future__ import annotations +import os, re, sys +from dataclasses import dataclass + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + + +@dataclass +class GradeResult: + reward: float + method: str + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str): + if not s: + return None + m = _NUMERIC_RE.search(str(s).replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol + + +def _is_clean_number(s: str) -> bool: + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False + + +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # Tier 1: exact + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if _num_close(g, c, abs_tol, rel_tol): + return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") + + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls(): + try: + with open("/workdir/.n_tool_calls") as fh: + return int(fh.read().strip()) + except (OSError, ValueError): + pass + raw = os.environ.get("N_TOOL_CALLS") + if raw is not None: + try: + return int(str(raw).strip()) + except ValueError: + return None + return None + + +def _tool_efficiency(n): + if n is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n / budget)) + + +def _tols(): + def _f(name): + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +def main_json() -> int: + import json + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + return 0 + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0043_512_43512681_qa_2/tests/test.sh b/tasks/0043_512_43512681_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0043_512_43512681_qa_2/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0043_512_43512681_qa_5/tests/grader.py b/tasks/0043_512_43512681_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0043_512_43512681_qa_5/tests/grader.py +++ b/tasks/0043_512_43512681_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/0043_644_43644485_qa_5/tests/grader.py b/tasks/0043_644_43644485_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0043_644_43644485_qa_5/tests/grader.py +++ b/tasks/0043_644_43644485_qa_5/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0043_936_43936231_qa_2/tests/grader.py b/tasks/0043_936_43936231_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0043_936_43936231_qa_2/tests/grader.py +++ b/tasks/0043_936_43936231_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/0043_969_43969595_qa_4/tests/grader.py b/tasks/0043_969_43969595_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0043_969_43969595_qa_4/tests/grader.py +++ b/tasks/0043_969_43969595_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/0044_401_44401900_qa_2/tests/grader.py b/tasks/0044_401_44401900_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0044_401_44401900_qa_2/tests/grader.py +++ b/tasks/0044_401_44401900_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_609_44609132_qa_3/tests/grader.py b/tasks/0044_609_44609132_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0044_609_44609132_qa_3/tests/grader.py +++ b/tasks/0044_609_44609132_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0044_954_44954372_qa_1/tests/grader.py b/tasks/0044_954_44954372_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0044_954_44954372_qa_1/tests/grader.py +++ b/tasks/0044_954_44954372_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_433_45433575_qa_3/tests/grader.py b/tasks/0045_433_45433575_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0045_433_45433575_qa_3/tests/grader.py +++ b/tasks/0045_433_45433575_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/0047_271_47271508_qa_5/tests/grader.py b/tasks/0047_271_47271508_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0047_271_47271508_qa_5/tests/grader.py +++ b/tasks/0047_271_47271508_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/0049_090_49090832_qa_1/tests/grader.py b/tasks/0049_090_49090832_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0049_090_49090832_qa_1/tests/grader.py +++ b/tasks/0049_090_49090832_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/0049_513_49513248_qa_5/tests/grader.py b/tasks/0049_513_49513248_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0049_513_49513248_qa_5/tests/grader.py +++ b/tasks/0049_513_49513248_qa_5/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0049_820_49820417_qa_1/tests/grader.py b/tasks/0049_820_49820417_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0049_820_49820417_qa_1/tests/grader.py +++ b/tasks/0049_820_49820417_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_842_50842241_qa_5/tests/grader.py b/tasks/0050_842_50842241_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0050_842_50842241_qa_5/tests/grader.py +++ b/tasks/0050_842_50842241_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_162_51162029_qa_3/environment/Dockerfile b/tasks/0051_162_51162029_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0051_162_51162029_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0051_162_51162029_qa_3/environment/pull_bucket.py b/tasks/0051_162_51162029_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0051_162_51162029_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/0051_162_51162029_qa_3/tests/grader.py b/tasks/0051_162_51162029_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0051_162_51162029_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/0051_162_51162029_qa_3/tests/test.sh b/tasks/0051_162_51162029_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0051_162_51162029_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/0052_313_52313444_qa_4/tests/grader.py b/tasks/0052_313_52313444_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0052_313_52313444_qa_4/tests/grader.py +++ b/tasks/0052_313_52313444_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_512_52512591_qa_4/tests/grader.py b/tasks/0052_512_52512591_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0052_512_52512591_qa_4/tests/grader.py +++ b/tasks/0052_512_52512591_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/0053_024_53024023_qa_1/tests/grader.py b/tasks/0053_024_53024023_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0053_024_53024023_qa_1/tests/grader.py +++ b/tasks/0053_024_53024023_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_842_53842474_qa_2/tests/grader.py b/tasks/0053_842_53842474_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0053_842_53842474_qa_2/tests/grader.py +++ b/tasks/0053_842_53842474_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/0054_670_54670437_qa_5/tests/grader.py b/tasks/0054_670_54670437_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0054_670_54670437_qa_5/tests/grader.py +++ b/tasks/0054_670_54670437_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/0055_042_55042891_qa_5/tests/grader.py b/tasks/0055_042_55042891_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0055_042_55042891_qa_5/tests/grader.py +++ b/tasks/0055_042_55042891_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/0055_335_55335995_qa_1/tests/grader.py b/tasks/0055_335_55335995_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0055_335_55335995_qa_1/tests/grader.py +++ b/tasks/0055_335_55335995_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/0056_526_56526864_qa_2/tests/grader.py b/tasks/0056_526_56526864_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0056_526_56526864_qa_2/tests/grader.py +++ b/tasks/0056_526_56526864_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0058_169_58169113_qa_4/tests/grader.py b/tasks/0058_169_58169113_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0058_169_58169113_qa_4/tests/grader.py +++ b/tasks/0058_169_58169113_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/0058_641_58641810_qa_2/tests/grader.py b/tasks/0058_641_58641810_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0058_641_58641810_qa_2/tests/grader.py +++ b/tasks/0058_641_58641810_qa_2/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0058_801_58801372_qa_2/tests/grader.py b/tasks/0058_801_58801372_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0058_801_58801372_qa_2/tests/grader.py +++ b/tasks/0058_801_58801372_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0060_331_60331255_qa_3/tests/grader.py b/tasks/0060_331_60331255_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0060_331_60331255_qa_3/tests/grader.py +++ b/tasks/0060_331_60331255_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_331_60331255_qa_4/environment/Dockerfile b/tasks/0060_331_60331255_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0060_331_60331255_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0060_331_60331255_qa_4/environment/pull_bucket.py b/tasks/0060_331_60331255_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0060_331_60331255_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/0060_331_60331255_qa_4/tests/grader.py b/tasks/0060_331_60331255_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0060_331_60331255_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/0060_331_60331255_qa_4/tests/test.sh b/tasks/0060_331_60331255_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0060_331_60331255_qa_4/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0060_418_60418523_qa_5/tests/grader.py b/tasks/0060_418_60418523_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0060_418_60418523_qa_5/tests/grader.py +++ b/tasks/0060_418_60418523_qa_5/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0061_041_61041621_qa_5/tests/grader.py b/tasks/0061_041_61041621_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0061_041_61041621_qa_5/tests/grader.py +++ b/tasks/0061_041_61041621_qa_5/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0061_208_61208833_qa_5/tests/grader.py b/tasks/0061_208_61208833_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0061_208_61208833_qa_5/tests/grader.py +++ b/tasks/0061_208_61208833_qa_5/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0061_330_61330810_qa_1/tests/grader.py b/tasks/0061_330_61330810_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0061_330_61330810_qa_1/tests/grader.py +++ b/tasks/0061_330_61330810_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0061_362_61362835_qa_2/tests/grader.py b/tasks/0061_362_61362835_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0061_362_61362835_qa_2/tests/grader.py +++ b/tasks/0061_362_61362835_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/0062_545_62545707_qa_1/tests/grader.py b/tasks/0062_545_62545707_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0062_545_62545707_qa_1/tests/grader.py +++ b/tasks/0062_545_62545707_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0064_232_64232136_qa_1/environment/Dockerfile b/tasks/0064_232_64232136_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0064_232_64232136_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0064_232_64232136_qa_1/environment/pull_bucket.py b/tasks/0064_232_64232136_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0064_232_64232136_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/0064_232_64232136_qa_1/tests/grader.py b/tasks/0064_232_64232136_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0064_232_64232136_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/0064_232_64232136_qa_1/tests/test.sh b/tasks/0064_232_64232136_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0064_232_64232136_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/0064_267_64267004_qa_5/tests/grader.py b/tasks/0064_267_64267004_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0064_267_64267004_qa_5/tests/grader.py +++ b/tasks/0064_267_64267004_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_766_64766227_qa_3/tests/grader.py b/tasks/0064_766_64766227_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0064_766_64766227_qa_3/tests/grader.py +++ b/tasks/0064_766_64766227_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0065_069_65069276_qa_1/environment/Dockerfile b/tasks/0065_069_65069276_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0065_069_65069276_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0065_069_65069276_qa_1/environment/pull_bucket.py b/tasks/0065_069_65069276_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0065_069_65069276_qa_1/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0065_069_65069276_qa_1/tests/grader.py b/tasks/0065_069_65069276_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0065_069_65069276_qa_1/tests/grader.py @@ -0,0 +1,172 @@ +"""Deterministic short-answer grader v2 — NO LLM judge. + +Tiers (all offline/deterministic): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) +""" +from __future__ import annotations +import os, re, sys +from dataclasses import dataclass + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + + +@dataclass +class GradeResult: + reward: float + method: str + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str): + if not s: + return None + m = _NUMERIC_RE.search(str(s).replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol + + +def _is_clean_number(s: str) -> bool: + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False + + +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # Tier 1: exact + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if _num_close(g, c, abs_tol, rel_tol): + return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") + + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls(): + try: + with open("/workdir/.n_tool_calls") as fh: + return int(fh.read().strip()) + except (OSError, ValueError): + pass + raw = os.environ.get("N_TOOL_CALLS") + if raw is not None: + try: + return int(str(raw).strip()) + except ValueError: + return None + return None + + +def _tool_efficiency(n): + if n is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n / budget)) + + +def _tols(): + def _f(name): + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +def main_json() -> int: + import json + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + return 0 + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0065_069_65069276_qa_1/tests/test.sh b/tasks/0065_069_65069276_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0065_069_65069276_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/0065_366_65366007_qa_1/tests/grader.py b/tasks/0065_366_65366007_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0065_366_65366007_qa_1/tests/grader.py +++ b/tasks/0065_366_65366007_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/0067_450_67450009_qa_1/tests/grader.py b/tasks/0067_450_67450009_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0067_450_67450009_qa_1/tests/grader.py +++ b/tasks/0067_450_67450009_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/0067_492_67492049_qa_4/tests/grader.py b/tasks/0067_492_67492049_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0067_492_67492049_qa_4/tests/grader.py +++ b/tasks/0067_492_67492049_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_675_67675814_qa_2/tests/grader.py b/tasks/0067_675_67675814_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0067_675_67675814_qa_2/tests/grader.py +++ b/tasks/0067_675_67675814_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_675_67675814_qa_5/tests/grader.py b/tasks/0067_675_67675814_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0067_675_67675814_qa_5/tests/grader.py +++ b/tasks/0067_675_67675814_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/0067_933_67933757_qa_4/tests/grader.py b/tasks/0067_933_67933757_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0067_933_67933757_qa_4/tests/grader.py +++ b/tasks/0067_933_67933757_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/0068_022_68022478_qa_1/tests/grader.py b/tasks/0068_022_68022478_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0068_022_68022478_qa_1/tests/grader.py +++ b/tasks/0068_022_68022478_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0068_079_68079868_qa_1/tests/grader.py b/tasks/0068_079_68079868_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0068_079_68079868_qa_1/tests/grader.py +++ b/tasks/0068_079_68079868_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/0068_152_68152590_qa_3/tests/grader.py b/tasks/0068_152_68152590_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0068_152_68152590_qa_3/tests/grader.py +++ b/tasks/0068_152_68152590_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_152_68152590_qa_4/tests/grader.py b/tasks/0068_152_68152590_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0068_152_68152590_qa_4/tests/grader.py +++ b/tasks/0068_152_68152590_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/0069_338_69338582_qa_2/tests/grader.py b/tasks/0069_338_69338582_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0069_338_69338582_qa_2/tests/grader.py +++ b/tasks/0069_338_69338582_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_397_69397859_qa_5/tests/grader.py b/tasks/0069_397_69397859_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0069_397_69397859_qa_5/tests/grader.py +++ b/tasks/0069_397_69397859_qa_5/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0072_216_72216676_qa_1/tests/grader.py b/tasks/0072_216_72216676_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0072_216_72216676_qa_1/tests/grader.py +++ b/tasks/0072_216_72216676_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/0073_172_73172053_qa_5/tests/grader.py b/tasks/0073_172_73172053_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0073_172_73172053_qa_5/tests/grader.py +++ b/tasks/0073_172_73172053_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/0073_796_73796901_qa_2/tests/grader.py b/tasks/0073_796_73796901_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0073_796_73796901_qa_2/tests/grader.py +++ b/tasks/0073_796_73796901_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/0073_901_73901899_qa_3/tests/grader.py b/tasks/0073_901_73901899_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0073_901_73901899_qa_3/tests/grader.py +++ b/tasks/0073_901_73901899_qa_3/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0074_281_74281388_qa_1/tests/grader.py b/tasks/0074_281_74281388_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0074_281_74281388_qa_1/tests/grader.py +++ b/tasks/0074_281_74281388_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/0074_406_74406391_qa_3/tests/grader.py b/tasks/0074_406_74406391_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0074_406_74406391_qa_3/tests/grader.py +++ b/tasks/0074_406_74406391_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0074_549_74549731_qa_3/tests/grader.py b/tasks/0074_549_74549731_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0074_549_74549731_qa_3/tests/grader.py +++ b/tasks/0074_549_74549731_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/0075_174_75174860_qa_2/tests/grader.py b/tasks/0075_174_75174860_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0075_174_75174860_qa_2/tests/grader.py +++ b/tasks/0075_174_75174860_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/0076_883_76883860_qa_2/tests/grader.py b/tasks/0076_883_76883860_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0076_883_76883860_qa_2/tests/grader.py +++ b/tasks/0076_883_76883860_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0077_497_77497432_qa_2/tests/grader.py b/tasks/0077_497_77497432_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0077_497_77497432_qa_2/tests/grader.py +++ b/tasks/0077_497_77497432_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0077_724_77724747_qa_3/tests/grader.py b/tasks/0077_724_77724747_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0077_724_77724747_qa_3/tests/grader.py +++ b/tasks/0077_724_77724747_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0079_509_79509130_qa_3/tests/grader.py b/tasks/0079_509_79509130_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0079_509_79509130_qa_3/tests/grader.py +++ b/tasks/0079_509_79509130_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/0080_832_80832047_qa_1/tests/grader.py b/tasks/0080_832_80832047_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0080_832_80832047_qa_1/tests/grader.py +++ b/tasks/0080_832_80832047_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/0082_858_82858946_qa_5/tests/grader.py b/tasks/0082_858_82858946_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0082_858_82858946_qa_5/tests/grader.py +++ b/tasks/0082_858_82858946_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_727_84727795_qa_4/environment/Dockerfile b/tasks/0084_727_84727795_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0084_727_84727795_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0084_727_84727795_qa_4/environment/pull_bucket.py b/tasks/0084_727_84727795_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0084_727_84727795_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/0084_727_84727795_qa_4/tests/grader.py b/tasks/0084_727_84727795_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0084_727_84727795_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/0084_727_84727795_qa_4/tests/test.sh b/tasks/0084_727_84727795_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0084_727_84727795_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/0084_772_84772070_qa_5/tests/grader.py b/tasks/0084_772_84772070_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0084_772_84772070_qa_5/tests/grader.py +++ b/tasks/0084_772_84772070_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/0084_827_84827302_qa_2/environment/Dockerfile b/tasks/0084_827_84827302_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0084_827_84827302_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0084_827_84827302_qa_2/environment/pull_bucket.py b/tasks/0084_827_84827302_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0084_827_84827302_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/0084_827_84827302_qa_2/tests/grader.py b/tasks/0084_827_84827302_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0084_827_84827302_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/0084_827_84827302_qa_2/tests/test.sh b/tasks/0084_827_84827302_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0084_827_84827302_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/0084_834_84834261_qa_3/tests/grader.py b/tasks/0084_834_84834261_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0084_834_84834261_qa_3/tests/grader.py +++ b/tasks/0084_834_84834261_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/0084_834_84834261_qa_4/tests/grader.py b/tasks/0084_834_84834261_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0084_834_84834261_qa_4/tests/grader.py +++ b/tasks/0084_834_84834261_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/0084_985_84985340_qa_2/tests/grader.py b/tasks/0084_985_84985340_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0084_985_84985340_qa_2/tests/grader.py +++ b/tasks/0084_985_84985340_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/0085_154_85154775_qa_3/tests/grader.py b/tasks/0085_154_85154775_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0085_154_85154775_qa_3/tests/grader.py +++ b/tasks/0085_154_85154775_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/0085_232_85232231_qa_3/tests/grader.py b/tasks/0085_232_85232231_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0085_232_85232231_qa_3/tests/grader.py +++ b/tasks/0085_232_85232231_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/0085_383_85383242_qa_5/tests/grader.py b/tasks/0085_383_85383242_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0085_383_85383242_qa_5/tests/grader.py +++ b/tasks/0085_383_85383242_qa_5/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0085_583_85583016_qa_1/tests/grader.py b/tasks/0085_583_85583016_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0085_583_85583016_qa_1/tests/grader.py +++ b/tasks/0085_583_85583016_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_903_85903605_qa_2/tests/grader.py b/tasks/0085_903_85903605_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0085_903_85903605_qa_2/tests/grader.py +++ b/tasks/0085_903_85903605_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/0085_903_85903605_qa_5/tests/grader.py b/tasks/0085_903_85903605_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0085_903_85903605_qa_5/tests/grader.py +++ b/tasks/0085_903_85903605_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/0086_381_86381271_qa_1/tests/grader.py b/tasks/0086_381_86381271_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0086_381_86381271_qa_1/tests/grader.py +++ b/tasks/0086_381_86381271_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/0086_531_86531254_qa_3/tests/grader.py b/tasks/0086_531_86531254_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0086_531_86531254_qa_3/tests/grader.py +++ b/tasks/0086_531_86531254_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_222_87222139_qa_2/tests/grader.py b/tasks/0087_222_87222139_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0087_222_87222139_qa_2/tests/grader.py +++ b/tasks/0087_222_87222139_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/0087_372_87372002_qa_2/tests/grader.py b/tasks/0087_372_87372002_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0087_372_87372002_qa_2/tests/grader.py +++ b/tasks/0087_372_87372002_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/0087_374_87374454_qa_3/tests/grader.py b/tasks/0087_374_87374454_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0087_374_87374454_qa_3/tests/grader.py +++ b/tasks/0087_374_87374454_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_973_87973029_qa_3/environment/Dockerfile b/tasks/0087_973_87973029_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0087_973_87973029_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0087_973_87973029_qa_3/environment/pull_bucket.py b/tasks/0087_973_87973029_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0087_973_87973029_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/0087_973_87973029_qa_3/tests/grader.py b/tasks/0087_973_87973029_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0087_973_87973029_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/0087_973_87973029_qa_3/tests/test.sh b/tasks/0087_973_87973029_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0087_973_87973029_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/0088_822_88822681_qa_1/tests/grader.py b/tasks/0088_822_88822681_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0088_822_88822681_qa_1/tests/grader.py +++ b/tasks/0088_822_88822681_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0089_775_89775918_qa_4/environment/Dockerfile b/tasks/0089_775_89775918_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0089_775_89775918_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0089_775_89775918_qa_4/environment/pull_bucket.py b/tasks/0089_775_89775918_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0089_775_89775918_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/0089_775_89775918_qa_4/tests/grader.py b/tasks/0089_775_89775918_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0089_775_89775918_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/0089_775_89775918_qa_4/tests/test.sh b/tasks/0089_775_89775918_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0089_775_89775918_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/0090_257_90257990_qa_4/tests/grader.py b/tasks/0090_257_90257990_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0090_257_90257990_qa_4/tests/grader.py +++ b/tasks/0090_257_90257990_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0090_285_90285188_qa_5/tests/grader.py b/tasks/0090_285_90285188_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0090_285_90285188_qa_5/tests/grader.py +++ b/tasks/0090_285_90285188_qa_5/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0090_301_90301818_qa_4/environment/Dockerfile b/tasks/0090_301_90301818_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0090_301_90301818_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0090_301_90301818_qa_4/environment/pull_bucket.py b/tasks/0090_301_90301818_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0090_301_90301818_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/0090_301_90301818_qa_4/tests/grader.py b/tasks/0090_301_90301818_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0090_301_90301818_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/0090_301_90301818_qa_4/tests/test.sh b/tasks/0090_301_90301818_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0090_301_90301818_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/0091_643_91643144_qa_2/tests/grader.py b/tasks/0091_643_91643144_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0091_643_91643144_qa_2/tests/grader.py +++ b/tasks/0091_643_91643144_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0091_643_91643144_qa_5/tests/grader.py b/tasks/0091_643_91643144_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0091_643_91643144_qa_5/tests/grader.py +++ b/tasks/0091_643_91643144_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/0091_670_91670414_qa_5/tests/grader.py b/tasks/0091_670_91670414_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0091_670_91670414_qa_5/tests/grader.py +++ b/tasks/0091_670_91670414_qa_5/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0091_774_91774768_qa_4/tests/grader.py b/tasks/0091_774_91774768_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0091_774_91774768_qa_4/tests/grader.py +++ b/tasks/0091_774_91774768_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/0092_190_92190264_qa_4/tests/grader.py b/tasks/0092_190_92190264_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0092_190_92190264_qa_4/tests/grader.py +++ b/tasks/0092_190_92190264_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/0092_596_92596170_qa_2/tests/grader.py b/tasks/0092_596_92596170_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0092_596_92596170_qa_2/tests/grader.py +++ b/tasks/0092_596_92596170_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0093_442_93442881_qa_2/tests/grader.py b/tasks/0093_442_93442881_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0093_442_93442881_qa_2/tests/grader.py +++ b/tasks/0093_442_93442881_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_765_96765273_qa_5/tests/grader.py b/tasks/0096_765_96765273_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0096_765_96765273_qa_5/tests/grader.py +++ b/tasks/0096_765_96765273_qa_5/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0097_565_97565207_qa_4/tests/grader.py b/tasks/0097_565_97565207_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0097_565_97565207_qa_4/tests/grader.py +++ b/tasks/0097_565_97565207_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_4/environment/Dockerfile b/tasks/0099_540_99540799_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0099_540_99540799_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0099_540_99540799_qa_4/environment/pull_bucket.py b/tasks/0099_540_99540799_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0099_540_99540799_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/0099_540_99540799_qa_4/tests/grader.py b/tasks/0099_540_99540799_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0099_540_99540799_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/0099_540_99540799_qa_4/tests/test.sh b/tasks/0099_540_99540799_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0099_540_99540799_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/0099_701_99701449_qa_2/tests/grader.py b/tasks/0099_701_99701449_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0099_701_99701449_qa_2/tests/grader.py +++ b/tasks/0099_701_99701449_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_701_99701449_qa_5/environment/Dockerfile b/tasks/0099_701_99701449_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0099_701_99701449_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0099_701_99701449_qa_5/environment/pull_bucket.py b/tasks/0099_701_99701449_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0099_701_99701449_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/0099_701_99701449_qa_5/tests/grader.py b/tasks/0099_701_99701449_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0099_701_99701449_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/0099_701_99701449_qa_5/tests/test.sh b/tasks/0099_701_99701449_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0099_701_99701449_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/0100_322_100322575_qa_1/tests/grader.py b/tasks/0100_322_100322575_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0100_322_100322575_qa_1/tests/grader.py +++ b/tasks/0100_322_100322575_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/0100_352_100352234_qa_4/tests/grader.py b/tasks/0100_352_100352234_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0100_352_100352234_qa_4/tests/grader.py +++ b/tasks/0100_352_100352234_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/0101_994_101994234_qa_2/tests/grader.py b/tasks/0101_994_101994234_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0101_994_101994234_qa_2/tests/grader.py +++ b/tasks/0101_994_101994234_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0102_401_102401343_qa_1/tests/grader.py b/tasks/0102_401_102401343_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0102_401_102401343_qa_1/tests/grader.py +++ b/tasks/0102_401_102401343_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_483_102483504_qa_3/tests/grader.py b/tasks/0102_483_102483504_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0102_483_102483504_qa_3/tests/grader.py +++ b/tasks/0102_483_102483504_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0103_134_103134692_qa_1/tests/grader.py b/tasks/0103_134_103134692_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0103_134_103134692_qa_1/tests/grader.py +++ b/tasks/0103_134_103134692_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0103_361_103361984_qa_1/environment/Dockerfile b/tasks/0103_361_103361984_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0103_361_103361984_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0103_361_103361984_qa_1/environment/pull_bucket.py b/tasks/0103_361_103361984_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0103_361_103361984_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/0103_361_103361984_qa_1/tests/grader.py b/tasks/0103_361_103361984_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0103_361_103361984_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/0103_361_103361984_qa_1/tests/test.sh b/tasks/0103_361_103361984_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0103_361_103361984_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/0103_452_103452394_qa_2/tests/grader.py b/tasks/0103_452_103452394_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0103_452_103452394_qa_2/tests/grader.py +++ b/tasks/0103_452_103452394_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/0103_514_103514732_qa_4/tests/grader.py b/tasks/0103_514_103514732_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0103_514_103514732_qa_4/tests/grader.py +++ b/tasks/0103_514_103514732_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0103_567_103567040_qa_3/tests/grader.py b/tasks/0103_567_103567040_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0103_567_103567040_qa_3/tests/grader.py +++ b/tasks/0103_567_103567040_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_115_104115755_qa_3/tests/grader.py b/tasks/0104_115_104115755_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0104_115_104115755_qa_3/tests/grader.py +++ b/tasks/0104_115_104115755_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_115_104115755_qa_4/tests/grader.py b/tasks/0104_115_104115755_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0104_115_104115755_qa_4/tests/grader.py +++ b/tasks/0104_115_104115755_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0104_919_104919033_qa_4/tests/grader.py b/tasks/0104_919_104919033_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0104_919_104919033_qa_4/tests/grader.py +++ b/tasks/0104_919_104919033_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0105_079_105079385_qa_4/tests/grader.py b/tasks/0105_079_105079385_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0105_079_105079385_qa_4/tests/grader.py +++ b/tasks/0105_079_105079385_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0105_332_105332394_qa_3/tests/grader.py b/tasks/0105_332_105332394_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0105_332_105332394_qa_3/tests/grader.py +++ b/tasks/0105_332_105332394_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/0105_388_105388778_qa_3/environment/Dockerfile b/tasks/0105_388_105388778_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0105_388_105388778_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0105_388_105388778_qa_3/environment/pull_bucket.py b/tasks/0105_388_105388778_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0105_388_105388778_qa_3/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0105_388_105388778_qa_3/tests/grader.py b/tasks/0105_388_105388778_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0105_388_105388778_qa_3/tests/grader.py @@ -0,0 +1,172 @@ +"""Deterministic short-answer grader v2 — NO LLM judge. + +Tiers (all offline/deterministic): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) +""" +from __future__ import annotations +import os, re, sys +from dataclasses import dataclass + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + + +@dataclass +class GradeResult: + reward: float + method: str + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str): + if not s: + return None + m = _NUMERIC_RE.search(str(s).replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol + + +def _is_clean_number(s: str) -> bool: + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False + + +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # Tier 1: exact + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if _num_close(g, c, abs_tol, rel_tol): + return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") + + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls(): + try: + with open("/workdir/.n_tool_calls") as fh: + return int(fh.read().strip()) + except (OSError, ValueError): + pass + raw = os.environ.get("N_TOOL_CALLS") + if raw is not None: + try: + return int(str(raw).strip()) + except ValueError: + return None + return None + + +def _tool_efficiency(n): + if n is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n / budget)) + + +def _tols(): + def _f(name): + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +def main_json() -> int: + import json + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + return 0 + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0105_388_105388778_qa_3/tests/test.sh b/tasks/0105_388_105388778_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0105_388_105388778_qa_3/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0105_477_105477138_qa_1/tests/grader.py b/tasks/0105_477_105477138_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0105_477_105477138_qa_1/tests/grader.py +++ b/tasks/0105_477_105477138_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0106_911_106911187_qa_4/tests/grader.py b/tasks/0106_911_106911187_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0106_911_106911187_qa_4/tests/grader.py +++ b/tasks/0106_911_106911187_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/0107_118_107118417_qa_3/tests/grader.py b/tasks/0107_118_107118417_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0107_118_107118417_qa_3/tests/grader.py +++ b/tasks/0107_118_107118417_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/0107_946_107946533_qa_1/tests/grader.py b/tasks/0107_946_107946533_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0107_946_107946533_qa_1/tests/grader.py +++ b/tasks/0107_946_107946533_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0108_781_108781422_qa_2/tests/grader.py b/tasks/0108_781_108781422_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0108_781_108781422_qa_2/tests/grader.py +++ b/tasks/0108_781_108781422_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/0108_883_108883493_qa_4/tests/grader.py b/tasks/0108_883_108883493_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0108_883_108883493_qa_4/tests/grader.py +++ b/tasks/0108_883_108883493_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/0109_303_109303873_qa_3/tests/grader.py b/tasks/0109_303_109303873_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0109_303_109303873_qa_3/tests/grader.py +++ b/tasks/0109_303_109303873_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/0109_525_109525152_qa_1/tests/grader.py b/tasks/0109_525_109525152_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0109_525_109525152_qa_1/tests/grader.py +++ b/tasks/0109_525_109525152_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0111_306_111306567_qa_5/tests/grader.py b/tasks/0111_306_111306567_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0111_306_111306567_qa_5/tests/grader.py +++ b/tasks/0111_306_111306567_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/0111_571_111571326_qa_2/tests/grader.py b/tasks/0111_571_111571326_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0111_571_111571326_qa_2/tests/grader.py +++ b/tasks/0111_571_111571326_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/0111_668_111668245_qa_3/tests/grader.py b/tasks/0111_668_111668245_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0111_668_111668245_qa_3/tests/grader.py +++ b/tasks/0111_668_111668245_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/0112_660_112660335_qa_2/tests/grader.py b/tasks/0112_660_112660335_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0112_660_112660335_qa_2/tests/grader.py +++ b/tasks/0112_660_112660335_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/0112_848_112848989_qa_4/tests/grader.py b/tasks/0112_848_112848989_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0112_848_112848989_qa_4/tests/grader.py +++ b/tasks/0112_848_112848989_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0113_075_113075841_qa_3/tests/grader.py b/tasks/0113_075_113075841_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0113_075_113075841_qa_3/tests/grader.py +++ b/tasks/0113_075_113075841_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0113_299_113299761_qa_1/tests/grader.py b/tasks/0113_299_113299761_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0113_299_113299761_qa_1/tests/grader.py +++ b/tasks/0113_299_113299761_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/0113_504_113504478_qa_3/tests/grader.py b/tasks/0113_504_113504478_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0113_504_113504478_qa_3/tests/grader.py +++ b/tasks/0113_504_113504478_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/0113_633_113633083_qa_5/tests/grader.py b/tasks/0113_633_113633083_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0113_633_113633083_qa_5/tests/grader.py +++ b/tasks/0113_633_113633083_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/0113_929_113929776_qa_2/tests/grader.py b/tasks/0113_929_113929776_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0113_929_113929776_qa_2/tests/grader.py +++ b/tasks/0113_929_113929776_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/0113_929_113929776_qa_5/environment/Dockerfile b/tasks/0113_929_113929776_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0113_929_113929776_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0113_929_113929776_qa_5/environment/pull_bucket.py b/tasks/0113_929_113929776_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0113_929_113929776_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/0113_929_113929776_qa_5/tests/grader.py b/tasks/0113_929_113929776_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0113_929_113929776_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/0113_929_113929776_qa_5/tests/test.sh b/tasks/0113_929_113929776_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0113_929_113929776_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/0113_941_113941848_qa_4/tests/grader.py b/tasks/0113_941_113941848_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0113_941_113941848_qa_4/tests/grader.py +++ b/tasks/0113_941_113941848_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/0114_484_114484829_qa_4/tests/grader.py b/tasks/0114_484_114484829_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0114_484_114484829_qa_4/tests/grader.py +++ b/tasks/0114_484_114484829_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/0114_618_114618907_qa_2/tests/grader.py b/tasks/0114_618_114618907_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0114_618_114618907_qa_2/tests/grader.py +++ b/tasks/0114_618_114618907_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0115_634_115634779_qa_3/tests/grader.py b/tasks/0115_634_115634779_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0115_634_115634779_qa_3/tests/grader.py +++ b/tasks/0115_634_115634779_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_634_115634779_qa_4/tests/grader.py b/tasks/0115_634_115634779_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0115_634_115634779_qa_4/tests/grader.py +++ b/tasks/0115_634_115634779_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/0115_814_115814701_qa_4/tests/grader.py b/tasks/0115_814_115814701_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0115_814_115814701_qa_4/tests/grader.py +++ b/tasks/0115_814_115814701_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/0116_026_116026387_qa_5/tests/grader.py b/tasks/0116_026_116026387_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0116_026_116026387_qa_5/tests/grader.py +++ b/tasks/0116_026_116026387_qa_5/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0120_313_120313409_qa_1/tests/grader.py b/tasks/0120_313_120313409_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0120_313_120313409_qa_1/tests/grader.py +++ b/tasks/0120_313_120313409_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0122_356_122356261_qa_2/tests/grader.py b/tasks/0122_356_122356261_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0122_356_122356261_qa_2/tests/grader.py +++ b/tasks/0122_356_122356261_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_625_123625013_qa_3/environment/Dockerfile b/tasks/0123_625_123625013_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0123_625_123625013_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0123_625_123625013_qa_3/environment/pull_bucket.py b/tasks/0123_625_123625013_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0123_625_123625013_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/0123_625_123625013_qa_3/tests/grader.py b/tasks/0123_625_123625013_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0123_625_123625013_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/0123_625_123625013_qa_3/tests/test.sh b/tasks/0123_625_123625013_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0123_625_123625013_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/0123_625_123625013_qa_4/tests/grader.py b/tasks/0123_625_123625013_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0123_625_123625013_qa_4/tests/grader.py +++ b/tasks/0123_625_123625013_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_643_123643083_qa_2/tests/grader.py b/tasks/0123_643_123643083_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0123_643_123643083_qa_2/tests/grader.py +++ b/tasks/0123_643_123643083_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/0124_615_124615899_qa_5/tests/grader.py b/tasks/0124_615_124615899_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0124_615_124615899_qa_5/tests/grader.py +++ b/tasks/0124_615_124615899_qa_5/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0124_965_124965722_qa_1/tests/grader.py b/tasks/0124_965_124965722_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0124_965_124965722_qa_1/tests/grader.py +++ b/tasks/0124_965_124965722_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/0126_019_126019687_qa_3/tests/grader.py b/tasks/0126_019_126019687_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0126_019_126019687_qa_3/tests/grader.py +++ b/tasks/0126_019_126019687_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/0126_066_126066478_qa_1/tests/grader.py b/tasks/0126_066_126066478_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0126_066_126066478_qa_1/tests/grader.py +++ b/tasks/0126_066_126066478_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/0126_687_126687596_qa_4/tests/grader.py b/tasks/0126_687_126687596_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0126_687_126687596_qa_4/tests/grader.py +++ b/tasks/0126_687_126687596_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/0126_746_126746817_qa_1/tests/grader.py b/tasks/0126_746_126746817_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0126_746_126746817_qa_1/tests/grader.py +++ b/tasks/0126_746_126746817_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_699_127699013_qa_2/tests/grader.py b/tasks/0127_699_127699013_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0127_699_127699013_qa_2/tests/grader.py +++ b/tasks/0127_699_127699013_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/0128_467_128467242_qa_1/tests/grader.py b/tasks/0128_467_128467242_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0128_467_128467242_qa_1/tests/grader.py +++ b/tasks/0128_467_128467242_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/0128_674_128674427_qa_5/tests/grader.py b/tasks/0128_674_128674427_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0128_674_128674427_qa_5/tests/grader.py +++ b/tasks/0128_674_128674427_qa_5/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0129_421_129421075_qa_4/environment/Dockerfile b/tasks/0129_421_129421075_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0129_421_129421075_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0129_421_129421075_qa_4/environment/pull_bucket.py b/tasks/0129_421_129421075_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0129_421_129421075_qa_4/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0129_421_129421075_qa_4/tests/grader.py b/tasks/0129_421_129421075_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0129_421_129421075_qa_4/tests/grader.py @@ -0,0 +1,172 @@ +"""Deterministic short-answer grader v2 — NO LLM judge. + +Tiers (all offline/deterministic): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) +""" +from __future__ import annotations +import os, re, sys +from dataclasses import dataclass + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + + +@dataclass +class GradeResult: + reward: float + method: str + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str): + if not s: + return None + m = _NUMERIC_RE.search(str(s).replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol + + +def _is_clean_number(s: str) -> bool: + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False + + +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # Tier 1: exact + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if _num_close(g, c, abs_tol, rel_tol): + return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") + + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls(): + try: + with open("/workdir/.n_tool_calls") as fh: + return int(fh.read().strip()) + except (OSError, ValueError): + pass + raw = os.environ.get("N_TOOL_CALLS") + if raw is not None: + try: + return int(str(raw).strip()) + except ValueError: + return None + return None + + +def _tool_efficiency(n): + if n is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n / budget)) + + +def _tols(): + def _f(name): + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +def main_json() -> int: + import json + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + return 0 + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0129_421_129421075_qa_4/tests/test.sh b/tasks/0129_421_129421075_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0129_421_129421075_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/0130_285_130285411_qa_1/tests/grader.py b/tasks/0130_285_130285411_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0130_285_130285411_qa_1/tests/grader.py +++ b/tasks/0130_285_130285411_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0132_642_132642166_qa_3/tests/grader.py b/tasks/0132_642_132642166_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0132_642_132642166_qa_3/tests/grader.py +++ b/tasks/0132_642_132642166_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0132_865_132865792_qa_4/tests/grader.py b/tasks/0132_865_132865792_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0132_865_132865792_qa_4/tests/grader.py +++ b/tasks/0132_865_132865792_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0135_355_135355749_qa_3/tests/grader.py b/tasks/0135_355_135355749_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0135_355_135355749_qa_3/tests/grader.py +++ b/tasks/0135_355_135355749_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0135_616_135616199_qa_4/tests/grader.py b/tasks/0135_616_135616199_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0135_616_135616199_qa_4/tests/grader.py +++ b/tasks/0135_616_135616199_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/0137_091_137091910_qa_3/tests/grader.py b/tasks/0137_091_137091910_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0137_091_137091910_qa_3/tests/grader.py +++ b/tasks/0137_091_137091910_qa_3/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0137_091_137091910_qa_4/tests/grader.py b/tasks/0137_091_137091910_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0137_091_137091910_qa_4/tests/grader.py +++ b/tasks/0137_091_137091910_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0138_435_138435541_qa_5/tests/grader.py b/tasks/0138_435_138435541_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0138_435_138435541_qa_5/tests/grader.py +++ b/tasks/0138_435_138435541_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_066_139066922_qa_2/tests/grader.py b/tasks/0139_066_139066922_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0139_066_139066922_qa_2/tests/grader.py +++ b/tasks/0139_066_139066922_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