diff --git a/tasks/0000_582_582934_qa_4/environment/Dockerfile b/tasks/0000_582_582934_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0000_582_582934_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0000_582_582934_qa_4/environment/pull_bucket.py b/tasks/0000_582_582934_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0000_582_582934_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/0000_582_582934_qa_4/tests/grader.py b/tasks/0000_582_582934_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0000_582_582934_qa_4/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", 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_582_582934_qa_4/tests/test.sh b/tasks/0000_582_582934_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0000_582_582934_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_105_1105892_qa_5/environment/Dockerfile b/tasks/0001_105_1105892_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_105_1105892_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_105_1105892_qa_5/environment/pull_bucket.py b/tasks/0001_105_1105892_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_105_1105892_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/0001_105_1105892_qa_5/tests/grader.py b/tasks/0001_105_1105892_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_105_1105892_qa_5/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", 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_105_1105892_qa_5/tests/test.sh b/tasks/0001_105_1105892_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_105_1105892_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/0001_261_1261978_qa_5/environment/Dockerfile b/tasks/0001_261_1261978_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_261_1261978_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_261_1261978_qa_5/environment/pull_bucket.py b/tasks/0001_261_1261978_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_261_1261978_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/0001_261_1261978_qa_5/tests/grader.py b/tasks/0001_261_1261978_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_261_1261978_qa_5/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", 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_261_1261978_qa_5/tests/test.sh b/tasks/0001_261_1261978_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_261_1261978_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/0001_439_1439907_qa_3/environment/Dockerfile b/tasks/0001_439_1439907_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_439_1439907_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_439_1439907_qa_3/environment/pull_bucket.py b/tasks/0001_439_1439907_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_439_1439907_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_439_1439907_qa_3/tests/grader.py b/tasks/0001_439_1439907_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_439_1439907_qa_3/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", 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_439_1439907_qa_3/tests/test.sh b/tasks/0001_439_1439907_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_439_1439907_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_487_1487950_qa_1/environment/Dockerfile b/tasks/0001_487_1487950_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_487_1487950_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_487_1487950_qa_1/environment/pull_bucket.py b/tasks/0001_487_1487950_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_487_1487950_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_487_1487950_qa_1/tests/grader.py b/tasks/0001_487_1487950_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_487_1487950_qa_1/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", 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_487_1487950_qa_1/tests/test.sh b/tasks/0001_487_1487950_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_487_1487950_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_533_1533644_qa_3/environment/Dockerfile b/tasks/0001_533_1533644_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_533_1533644_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_533_1533644_qa_3/environment/pull_bucket.py b/tasks/0001_533_1533644_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_533_1533644_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_533_1533644_qa_3/tests/grader.py b/tasks/0001_533_1533644_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_533_1533644_qa_3/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", 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_533_1533644_qa_3/tests/test.sh b/tasks/0001_533_1533644_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_533_1533644_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_683_1683832_qa_5/environment/Dockerfile b/tasks/0001_683_1683832_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_683_1683832_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_683_1683832_qa_5/environment/pull_bucket.py b/tasks/0001_683_1683832_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_683_1683832_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/0001_683_1683832_qa_5/tests/grader.py b/tasks/0001_683_1683832_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_683_1683832_qa_5/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", 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_683_1683832_qa_5/tests/test.sh b/tasks/0001_683_1683832_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_683_1683832_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/0001_727_1727043_qa_4/environment/Dockerfile b/tasks/0001_727_1727043_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_727_1727043_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_727_1727043_qa_4/environment/pull_bucket.py b/tasks/0001_727_1727043_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_727_1727043_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_727_1727043_qa_4/tests/grader.py b/tasks/0001_727_1727043_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_727_1727043_qa_4/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", 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_727_1727043_qa_4/tests/test.sh b/tasks/0001_727_1727043_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_727_1727043_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_735_1735855_qa_3/environment/Dockerfile b/tasks/0001_735_1735855_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_735_1735855_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_735_1735855_qa_3/environment/pull_bucket.py b/tasks/0001_735_1735855_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_735_1735855_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_735_1735855_qa_3/tests/grader.py b/tasks/0001_735_1735855_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_735_1735855_qa_3/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", 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_735_1735855_qa_3/tests/test.sh b/tasks/0001_735_1735855_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_735_1735855_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/0002_092_2092240_qa_5/environment/Dockerfile b/tasks/0002_092_2092240_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0002_092_2092240_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0002_092_2092240_qa_5/environment/pull_bucket.py b/tasks/0002_092_2092240_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0002_092_2092240_qa_5/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0002_092_2092240_qa_5/tests/grader.py b/tasks/0002_092_2092240_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0002_092_2092240_qa_5/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0002_092_2092240_qa_5/tests/test.sh b/tasks/0002_092_2092240_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0002_092_2092240_qa_5/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0021_135_21135636_qa_3/environment/Dockerfile b/tasks/0021_135_21135636_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0021_135_21135636_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0021_135_21135636_qa_3/environment/pull_bucket.py b/tasks/0021_135_21135636_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0021_135_21135636_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_135_21135636_qa_3/tests/grader.py b/tasks/0021_135_21135636_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0021_135_21135636_qa_3/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", 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_135_21135636_qa_3/tests/test.sh b/tasks/0021_135_21135636_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0021_135_21135636_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/0021_656_21656365_qa_5/environment/Dockerfile b/tasks/0021_656_21656365_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0021_656_21656365_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0021_656_21656365_qa_5/environment/pull_bucket.py b/tasks/0021_656_21656365_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0021_656_21656365_qa_5/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0021_656_21656365_qa_5/tests/grader.py b/tasks/0021_656_21656365_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0021_656_21656365_qa_5/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", 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_656_21656365_qa_5/tests/test.sh b/tasks/0021_656_21656365_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0021_656_21656365_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/0023_757_23757075_qa_3/environment/pull_bucket.py b/tasks/0023_757_23757075_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0023_757_23757075_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/0033_308_33308132_qa_3/environment/Dockerfile b/tasks/0033_308_33308132_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0033_308_33308132_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0033_308_33308132_qa_3/environment/pull_bucket.py b/tasks/0033_308_33308132_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0033_308_33308132_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/0033_308_33308132_qa_3/tests/grader.py b/tasks/0033_308_33308132_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0033_308_33308132_qa_3/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", 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/0033_308_33308132_qa_3/tests/test.sh b/tasks/0033_308_33308132_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0033_308_33308132_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_810_39810505_qa_1/environment/Dockerfile b/tasks/0039_810_39810505_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0039_810_39810505_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0039_810_39810505_qa_1/environment/pull_bucket.py b/tasks/0039_810_39810505_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0039_810_39810505_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/0039_810_39810505_qa_1/tests/grader.py b/tasks/0039_810_39810505_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0039_810_39810505_qa_1/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", 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_810_39810505_qa_1/tests/test.sh b/tasks/0039_810_39810505_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0039_810_39810505_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/0040_713_40713386_qa_3/environment/Dockerfile b/tasks/0040_713_40713386_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0040_713_40713386_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0040_713_40713386_qa_3/environment/pull_bucket.py b/tasks/0040_713_40713386_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0040_713_40713386_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/0040_713_40713386_qa_3/tests/grader.py b/tasks/0040_713_40713386_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0040_713_40713386_qa_3/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", 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_713_40713386_qa_3/tests/test.sh b/tasks/0040_713_40713386_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0040_713_40713386_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/0040_748_40748661_qa_3/environment/Dockerfile b/tasks/0040_748_40748661_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0040_748_40748661_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0040_748_40748661_qa_3/environment/pull_bucket.py b/tasks/0040_748_40748661_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0040_748_40748661_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/0040_748_40748661_qa_3/tests/grader.py b/tasks/0040_748_40748661_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0040_748_40748661_qa_3/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", 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_748_40748661_qa_3/tests/test.sh b/tasks/0040_748_40748661_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0040_748_40748661_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/0040_880_40880494_qa_3/environment/Dockerfile b/tasks/0040_880_40880494_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0040_880_40880494_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0040_880_40880494_qa_3/environment/pull_bucket.py b/tasks/0040_880_40880494_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0040_880_40880494_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/0040_880_40880494_qa_3/tests/grader.py b/tasks/0040_880_40880494_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0040_880_40880494_qa_3/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", 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_880_40880494_qa_3/tests/test.sh b/tasks/0040_880_40880494_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0040_880_40880494_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_703_41703265_qa_5/environment/Dockerfile b/tasks/0041_703_41703265_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0041_703_41703265_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0041_703_41703265_qa_5/environment/pull_bucket.py b/tasks/0041_703_41703265_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0041_703_41703265_qa_5/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0041_703_41703265_qa_5/tests/grader.py b/tasks/0041_703_41703265_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0041_703_41703265_qa_5/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", 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_703_41703265_qa_5/tests/test.sh b/tasks/0041_703_41703265_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0041_703_41703265_qa_5/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0042_446_42446776_qa_5/environment/Dockerfile b/tasks/0042_446_42446776_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0042_446_42446776_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0042_446_42446776_qa_5/environment/pull_bucket.py b/tasks/0042_446_42446776_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0042_446_42446776_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/0042_446_42446776_qa_5/tests/grader.py b/tasks/0042_446_42446776_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0042_446_42446776_qa_5/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", 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/0042_446_42446776_qa_5/tests/test.sh b/tasks/0042_446_42446776_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0042_446_42446776_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/0045_409_45409591_qa_4/environment/Dockerfile b/tasks/0045_409_45409591_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0045_409_45409591_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0045_409_45409591_qa_4/environment/pull_bucket.py b/tasks/0045_409_45409591_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0045_409_45409591_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/0045_409_45409591_qa_4/tests/grader.py b/tasks/0045_409_45409591_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0045_409_45409591_qa_4/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0045_409_45409591_qa_4/tests/test.sh b/tasks/0045_409_45409591_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0045_409_45409591_qa_4/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0047_417_47417997_qa_1/environment/Dockerfile b/tasks/0047_417_47417997_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0047_417_47417997_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0047_417_47417997_qa_1/environment/pull_bucket.py b/tasks/0047_417_47417997_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0047_417_47417997_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/0047_417_47417997_qa_1/tests/grader.py b/tasks/0047_417_47417997_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0047_417_47417997_qa_1/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0047_417_47417997_qa_1/tests/test.sh b/tasks/0047_417_47417997_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0047_417_47417997_qa_1/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0047_560_47560034_qa_1/environment/Dockerfile b/tasks/0047_560_47560034_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0047_560_47560034_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0047_560_47560034_qa_1/environment/pull_bucket.py b/tasks/0047_560_47560034_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0047_560_47560034_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/0047_560_47560034_qa_1/tests/grader.py b/tasks/0047_560_47560034_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0047_560_47560034_qa_1/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0047_560_47560034_qa_1/tests/test.sh b/tasks/0047_560_47560034_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0047_560_47560034_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/0048_049_48049467_qa_5/environment/Dockerfile b/tasks/0048_049_48049467_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0048_049_48049467_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0048_049_48049467_qa_5/environment/pull_bucket.py b/tasks/0048_049_48049467_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0048_049_48049467_qa_5/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0048_049_48049467_qa_5/tests/grader.py b/tasks/0048_049_48049467_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0048_049_48049467_qa_5/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0048_049_48049467_qa_5/tests/test.sh b/tasks/0048_049_48049467_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0048_049_48049467_qa_5/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0051_591_51591719_qa_1/environment/Dockerfile b/tasks/0051_591_51591719_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0051_591_51591719_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0051_591_51591719_qa_1/environment/pull_bucket.py b/tasks/0051_591_51591719_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0051_591_51591719_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/0051_591_51591719_qa_1/tests/grader.py b/tasks/0051_591_51591719_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0051_591_51591719_qa_1/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", 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_591_51591719_qa_1/tests/test.sh b/tasks/0051_591_51591719_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0051_591_51591719_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/0055_115_55115812_qa_1/environment/Dockerfile b/tasks/0055_115_55115812_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0055_115_55115812_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0055_115_55115812_qa_1/environment/pull_bucket.py b/tasks/0055_115_55115812_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0055_115_55115812_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/0055_115_55115812_qa_1/tests/grader.py b/tasks/0055_115_55115812_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0055_115_55115812_qa_1/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", 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/0055_115_55115812_qa_1/tests/test.sh b/tasks/0055_115_55115812_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0055_115_55115812_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/0058_924_58924130_qa_1/environment/Dockerfile b/tasks/0058_924_58924130_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0058_924_58924130_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0058_924_58924130_qa_1/environment/pull_bucket.py b/tasks/0058_924_58924130_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0058_924_58924130_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/0058_924_58924130_qa_1/tests/grader.py b/tasks/0058_924_58924130_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0058_924_58924130_qa_1/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0058_924_58924130_qa_1/tests/test.sh b/tasks/0058_924_58924130_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0058_924_58924130_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/0062_642_62642092_qa_5/environment/Dockerfile b/tasks/0062_642_62642092_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0062_642_62642092_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0062_642_62642092_qa_5/environment/pull_bucket.py b/tasks/0062_642_62642092_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0062_642_62642092_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/0062_642_62642092_qa_5/tests/grader.py b/tasks/0062_642_62642092_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0062_642_62642092_qa_5/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", 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/0062_642_62642092_qa_5/tests/test.sh b/tasks/0062_642_62642092_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0062_642_62642092_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/0064_084_64084849_qa_4/environment/Dockerfile b/tasks/0064_084_64084849_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0064_084_64084849_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0064_084_64084849_qa_4/environment/pull_bucket.py b/tasks/0064_084_64084849_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0064_084_64084849_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/0064_084_64084849_qa_4/tests/grader.py b/tasks/0064_084_64084849_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0064_084_64084849_qa_4/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", 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_084_64084849_qa_4/tests/test.sh b/tasks/0064_084_64084849_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0064_084_64084849_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/0064_496_64496303_qa_3/environment/Dockerfile b/tasks/0064_496_64496303_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0064_496_64496303_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0064_496_64496303_qa_3/environment/pull_bucket.py b/tasks/0064_496_64496303_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0064_496_64496303_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/0064_496_64496303_qa_3/tests/grader.py b/tasks/0064_496_64496303_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0064_496_64496303_qa_3/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", 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_496_64496303_qa_3/tests/test.sh b/tasks/0064_496_64496303_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0064_496_64496303_qa_3/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0065_166_65166426_qa_5/environment/Dockerfile b/tasks/0065_166_65166426_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0065_166_65166426_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0065_166_65166426_qa_5/environment/pull_bucket.py b/tasks/0065_166_65166426_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0065_166_65166426_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/0065_166_65166426_qa_5/tests/grader.py b/tasks/0065_166_65166426_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0065_166_65166426_qa_5/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", 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_166_65166426_qa_5/tests/test.sh b/tasks/0065_166_65166426_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0065_166_65166426_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/0066_107_66107048_qa_1/environment/Dockerfile b/tasks/0066_107_66107048_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0066_107_66107048_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0066_107_66107048_qa_1/environment/pull_bucket.py b/tasks/0066_107_66107048_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0066_107_66107048_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/0066_107_66107048_qa_1/tests/grader.py b/tasks/0066_107_66107048_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0066_107_66107048_qa_1/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0066_107_66107048_qa_1/tests/test.sh b/tasks/0066_107_66107048_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0066_107_66107048_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/0074_600_74600268_qa_2/environment/Dockerfile b/tasks/0074_600_74600268_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0074_600_74600268_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0074_600_74600268_qa_2/environment/pull_bucket.py b/tasks/0074_600_74600268_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0074_600_74600268_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/0074_600_74600268_qa_2/tests/grader.py b/tasks/0074_600_74600268_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0074_600_74600268_qa_2/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", 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/0074_600_74600268_qa_2/tests/test.sh b/tasks/0074_600_74600268_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0074_600_74600268_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/0074_999_74999890_qa_2/environment/Dockerfile b/tasks/0074_999_74999890_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0074_999_74999890_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0074_999_74999890_qa_2/environment/pull_bucket.py b/tasks/0074_999_74999890_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0074_999_74999890_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/0074_999_74999890_qa_2/tests/grader.py b/tasks/0074_999_74999890_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0074_999_74999890_qa_2/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", 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/0074_999_74999890_qa_2/tests/test.sh b/tasks/0074_999_74999890_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0074_999_74999890_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/0077_218_77218707_qa_3/environment/Dockerfile b/tasks/0077_218_77218707_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0077_218_77218707_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0077_218_77218707_qa_3/environment/pull_bucket.py b/tasks/0077_218_77218707_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0077_218_77218707_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/0077_218_77218707_qa_3/tests/grader.py b/tasks/0077_218_77218707_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0077_218_77218707_qa_3/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", 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/0077_218_77218707_qa_3/tests/test.sh b/tasks/0077_218_77218707_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0077_218_77218707_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/0080_832_80832047_qa_5/environment/Dockerfile b/tasks/0080_832_80832047_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0080_832_80832047_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0080_832_80832047_qa_5/environment/pull_bucket.py b/tasks/0080_832_80832047_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0080_832_80832047_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/0080_832_80832047_qa_5/tests/grader.py b/tasks/0080_832_80832047_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0080_832_80832047_qa_5/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0080_832_80832047_qa_5/tests/test.sh b/tasks/0080_832_80832047_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0080_832_80832047_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/0081_472_81472707_qa_3/environment/Dockerfile b/tasks/0081_472_81472707_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0081_472_81472707_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0081_472_81472707_qa_3/environment/pull_bucket.py b/tasks/0081_472_81472707_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0081_472_81472707_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/0081_472_81472707_qa_3/tests/grader.py b/tasks/0081_472_81472707_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0081_472_81472707_qa_3/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", 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/0081_472_81472707_qa_3/tests/test.sh b/tasks/0081_472_81472707_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0081_472_81472707_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/0087_643_87643226_qa_5/environment/Dockerfile b/tasks/0087_643_87643226_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0087_643_87643226_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0087_643_87643226_qa_5/environment/pull_bucket.py b/tasks/0087_643_87643226_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0087_643_87643226_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/0087_643_87643226_qa_5/tests/grader.py b/tasks/0087_643_87643226_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0087_643_87643226_qa_5/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", 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_643_87643226_qa_5/tests/test.sh b/tasks/0087_643_87643226_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0087_643_87643226_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/0092_424_92424981_qa_1/environment/Dockerfile b/tasks/0092_424_92424981_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0092_424_92424981_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0092_424_92424981_qa_1/environment/pull_bucket.py b/tasks/0092_424_92424981_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0092_424_92424981_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/0092_424_92424981_qa_1/tests/grader.py b/tasks/0092_424_92424981_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0092_424_92424981_qa_1/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0092_424_92424981_qa_1/tests/test.sh b/tasks/0092_424_92424981_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0092_424_92424981_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/0097_283_97283539_qa_3/environment/Dockerfile b/tasks/0097_283_97283539_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0097_283_97283539_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0097_283_97283539_qa_3/environment/pull_bucket.py b/tasks/0097_283_97283539_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0097_283_97283539_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/0097_283_97283539_qa_3/tests/grader.py b/tasks/0097_283_97283539_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0097_283_97283539_qa_3/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", 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/0097_283_97283539_qa_3/tests/test.sh b/tasks/0097_283_97283539_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0097_283_97283539_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/0100_115_100115013_qa_3/environment/Dockerfile b/tasks/0100_115_100115013_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0100_115_100115013_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0100_115_100115013_qa_3/environment/pull_bucket.py b/tasks/0100_115_100115013_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0100_115_100115013_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/0100_115_100115013_qa_3/tests/grader.py b/tasks/0100_115_100115013_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0100_115_100115013_qa_3/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", 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/0100_115_100115013_qa_3/tests/test.sh b/tasks/0100_115_100115013_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0100_115_100115013_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/0100_986_100986965_qa_5/environment/Dockerfile b/tasks/0100_986_100986965_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0100_986_100986965_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0100_986_100986965_qa_5/environment/pull_bucket.py b/tasks/0100_986_100986965_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0100_986_100986965_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/0100_986_100986965_qa_5/tests/grader.py b/tasks/0100_986_100986965_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0100_986_100986965_qa_5/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", 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/0100_986_100986965_qa_5/tests/test.sh b/tasks/0100_986_100986965_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0100_986_100986965_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/0103_134_103134692_qa_4/environment/Dockerfile b/tasks/0103_134_103134692_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0103_134_103134692_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0103_134_103134692_qa_4/environment/pull_bucket.py b/tasks/0103_134_103134692_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0103_134_103134692_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/0103_134_103134692_qa_4/tests/grader.py b/tasks/0103_134_103134692_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0103_134_103134692_qa_4/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", 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_134_103134692_qa_4/tests/test.sh b/tasks/0103_134_103134692_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0103_134_103134692_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/0103_502_103502811_qa_4/environment/Dockerfile b/tasks/0103_502_103502811_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0103_502_103502811_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0103_502_103502811_qa_4/environment/pull_bucket.py b/tasks/0103_502_103502811_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0103_502_103502811_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/0103_502_103502811_qa_4/tests/grader.py b/tasks/0103_502_103502811_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0103_502_103502811_qa_4/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", 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_502_103502811_qa_4/tests/test.sh b/tasks/0103_502_103502811_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0103_502_103502811_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/0110_937_110937668_qa_1/environment/Dockerfile b/tasks/0110_937_110937668_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0110_937_110937668_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0110_937_110937668_qa_1/environment/pull_bucket.py b/tasks/0110_937_110937668_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0110_937_110937668_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/0110_937_110937668_qa_1/tests/grader.py b/tasks/0110_937_110937668_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0110_937_110937668_qa_1/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", 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/0110_937_110937668_qa_1/tests/test.sh b/tasks/0110_937_110937668_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0110_937_110937668_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/0116_553_116553968_qa_1/environment/Dockerfile b/tasks/0116_553_116553968_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0116_553_116553968_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0116_553_116553968_qa_1/environment/pull_bucket.py b/tasks/0116_553_116553968_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0116_553_116553968_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/0116_553_116553968_qa_1/tests/grader.py b/tasks/0116_553_116553968_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0116_553_116553968_qa_1/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0116_553_116553968_qa_1/tests/test.sh b/tasks/0116_553_116553968_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0116_553_116553968_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/0117_137_117137785_qa_2/environment/Dockerfile b/tasks/0117_137_117137785_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0117_137_117137785_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0117_137_117137785_qa_2/environment/pull_bucket.py b/tasks/0117_137_117137785_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0117_137_117137785_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/0117_137_117137785_qa_2/tests/grader.py b/tasks/0117_137_117137785_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0117_137_117137785_qa_2/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", 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/0117_137_117137785_qa_2/tests/test.sh b/tasks/0117_137_117137785_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0117_137_117137785_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/0124_269_124269009_qa_3/environment/Dockerfile b/tasks/0124_269_124269009_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0124_269_124269009_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0124_269_124269009_qa_3/environment/pull_bucket.py b/tasks/0124_269_124269009_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0124_269_124269009_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/0124_269_124269009_qa_3/tests/grader.py b/tasks/0124_269_124269009_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0124_269_124269009_qa_3/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0124_269_124269009_qa_3/tests/test.sh b/tasks/0124_269_124269009_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0124_269_124269009_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/0133_533_133533460_qa_2/environment/Dockerfile b/tasks/0133_533_133533460_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0133_533_133533460_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0133_533_133533460_qa_2/environment/pull_bucket.py b/tasks/0133_533_133533460_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0133_533_133533460_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/0133_533_133533460_qa_2/tests/grader.py b/tasks/0133_533_133533460_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0133_533_133533460_qa_2/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0133_533_133533460_qa_2/tests/test.sh b/tasks/0133_533_133533460_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0133_533_133533460_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/0136_961_136961156_qa_5/environment/Dockerfile b/tasks/0136_961_136961156_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0136_961_136961156_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0136_961_136961156_qa_5/environment/pull_bucket.py b/tasks/0136_961_136961156_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0136_961_136961156_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/0136_961_136961156_qa_5/tests/grader.py b/tasks/0136_961_136961156_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0136_961_136961156_qa_5/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0136_961_136961156_qa_5/tests/test.sh b/tasks/0136_961_136961156_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0136_961_136961156_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/0138_103_138103420_qa_2/environment/Dockerfile b/tasks/0138_103_138103420_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0138_103_138103420_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0138_103_138103420_qa_2/environment/pull_bucket.py b/tasks/0138_103_138103420_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0138_103_138103420_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/0138_103_138103420_qa_2/tests/grader.py b/tasks/0138_103_138103420_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0138_103_138103420_qa_2/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + 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_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", 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/0138_103_138103420_qa_2/tests/test.sh b/tasks/0138_103_138103420_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0138_103_138103420_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