diff --git a/tasks/0000_376_376301_qa_1/environment/Dockerfile b/tasks/0000_376_376301_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0000_376_376301_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0000_376_376301_qa_1/environment/pull_bucket.py b/tasks/0000_376_376301_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0000_376_376301_qa_1/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0000_376_376301_qa_1/tests/grader.py b/tasks/0000_376_376301_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0000_376_376301_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/0000_376_376301_qa_1/tests/test.sh b/tasks/0000_376_376301_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0000_376_376301_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/0000_440_440038_qa_5/environment/Dockerfile b/tasks/0000_440_440038_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0000_440_440038_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0000_440_440038_qa_5/environment/pull_bucket.py b/tasks/0000_440_440038_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0000_440_440038_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/0000_440_440038_qa_5/tests/grader.py b/tasks/0000_440_440038_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0000_440_440038_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/0000_440_440038_qa_5/tests/test.sh b/tasks/0000_440_440038_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0000_440_440038_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/0000_545_545324_qa_1/environment/Dockerfile b/tasks/0000_545_545324_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0000_545_545324_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0000_545_545324_qa_1/environment/pull_bucket.py b/tasks/0000_545_545324_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0000_545_545324_qa_1/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0000_545_545324_qa_1/tests/grader.py b/tasks/0000_545_545324_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0000_545_545324_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/0000_545_545324_qa_1/tests/test.sh b/tasks/0000_545_545324_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0000_545_545324_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/0000_641_641256_qa_3/environment/Dockerfile b/tasks/0000_641_641256_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0000_641_641256_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0000_641_641256_qa_3/environment/pull_bucket.py b/tasks/0000_641_641256_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0000_641_641256_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/0000_641_641256_qa_3/tests/grader.py b/tasks/0000_641_641256_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0000_641_641256_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/0000_641_641256_qa_3/tests/test.sh b/tasks/0000_641_641256_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0000_641_641256_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/0000_647_647453_qa_3/environment/Dockerfile b/tasks/0000_647_647453_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0000_647_647453_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0000_647_647453_qa_3/environment/pull_bucket.py b/tasks/0000_647_647453_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0000_647_647453_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/0000_647_647453_qa_3/tests/grader.py b/tasks/0000_647_647453_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0000_647_647453_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/0000_647_647453_qa_3/tests/test.sh b/tasks/0000_647_647453_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0000_647_647453_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/0000_651_651325_qa_4/environment/Dockerfile b/tasks/0000_651_651325_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0000_651_651325_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0000_651_651325_qa_4/environment/pull_bucket.py b/tasks/0000_651_651325_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0000_651_651325_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_651_651325_qa_4/tests/grader.py b/tasks/0000_651_651325_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0000_651_651325_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_651_651325_qa_4/tests/test.sh b/tasks/0000_651_651325_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0000_651_651325_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/0000_682_682562_qa_2/environment/Dockerfile b/tasks/0000_682_682562_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0000_682_682562_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0000_682_682562_qa_2/environment/pull_bucket.py b/tasks/0000_682_682562_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0000_682_682562_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/0000_682_682562_qa_2/tests/grader.py b/tasks/0000_682_682562_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0000_682_682562_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/0000_682_682562_qa_2/tests/test.sh b/tasks/0000_682_682562_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0000_682_682562_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/0000_684_684849_qa_2/environment/Dockerfile b/tasks/0000_684_684849_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0000_684_684849_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0000_684_684849_qa_2/environment/pull_bucket.py b/tasks/0000_684_684849_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0000_684_684849_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/0000_684_684849_qa_2/tests/grader.py b/tasks/0000_684_684849_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0000_684_684849_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/0000_684_684849_qa_2/tests/test.sh b/tasks/0000_684_684849_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0000_684_684849_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/0000_689_689967_qa_5/environment/Dockerfile b/tasks/0000_689_689967_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0000_689_689967_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0000_689_689967_qa_5/environment/pull_bucket.py b/tasks/0000_689_689967_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0000_689_689967_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/0000_689_689967_qa_5/tests/grader.py b/tasks/0000_689_689967_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0000_689_689967_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/0000_689_689967_qa_5/tests/test.sh b/tasks/0000_689_689967_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0000_689_689967_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/0000_767_767688_qa_4/environment/Dockerfile b/tasks/0000_767_767688_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0000_767_767688_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0000_767_767688_qa_4/environment/pull_bucket.py b/tasks/0000_767_767688_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0000_767_767688_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_767_767688_qa_4/tests/grader.py b/tasks/0000_767_767688_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0000_767_767688_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_767_767688_qa_4/tests/test.sh b/tasks/0000_767_767688_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0000_767_767688_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/0000_780_780974_qa_2/environment/Dockerfile b/tasks/0000_780_780974_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0000_780_780974_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0000_780_780974_qa_2/environment/pull_bucket.py b/tasks/0000_780_780974_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0000_780_780974_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/0000_780_780974_qa_2/tests/grader.py b/tasks/0000_780_780974_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0000_780_780974_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/0000_780_780974_qa_2/tests/test.sh b/tasks/0000_780_780974_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0000_780_780974_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/0000_807_807075_qa_1/environment/Dockerfile b/tasks/0000_807_807075_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0000_807_807075_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0000_807_807075_qa_1/environment/pull_bucket.py b/tasks/0000_807_807075_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0000_807_807075_qa_1/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0000_807_807075_qa_1/tests/grader.py b/tasks/0000_807_807075_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0000_807_807075_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/0000_807_807075_qa_1/tests/test.sh b/tasks/0000_807_807075_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0000_807_807075_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/0000_812_812048_qa_2/environment/Dockerfile b/tasks/0000_812_812048_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0000_812_812048_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0000_812_812048_qa_2/environment/pull_bucket.py b/tasks/0000_812_812048_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0000_812_812048_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/0000_812_812048_qa_2/tests/grader.py b/tasks/0000_812_812048_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0000_812_812048_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/0000_812_812048_qa_2/tests/test.sh b/tasks/0000_812_812048_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0000_812_812048_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/0000_975_975906_qa_1/environment/Dockerfile b/tasks/0000_975_975906_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0000_975_975906_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0000_975_975906_qa_1/environment/pull_bucket.py b/tasks/0000_975_975906_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0000_975_975906_qa_1/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0000_975_975906_qa_1/tests/grader.py b/tasks/0000_975_975906_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0000_975_975906_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/0000_975_975906_qa_1/tests/test.sh b/tasks/0000_975_975906_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0000_975_975906_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_181_1181828_qa_3/environment/Dockerfile b/tasks/0001_181_1181828_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_181_1181828_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_181_1181828_qa_3/environment/pull_bucket.py b/tasks/0001_181_1181828_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_181_1181828_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_181_1181828_qa_3/tests/grader.py b/tasks/0001_181_1181828_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_181_1181828_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_181_1181828_qa_3/tests/test.sh b/tasks/0001_181_1181828_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_181_1181828_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_189_1189227_qa_5/environment/Dockerfile b/tasks/0001_189_1189227_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_189_1189227_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_189_1189227_qa_5/environment/pull_bucket.py b/tasks/0001_189_1189227_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_189_1189227_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_189_1189227_qa_5/tests/grader.py b/tasks/0001_189_1189227_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_189_1189227_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_189_1189227_qa_5/tests/test.sh b/tasks/0001_189_1189227_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_189_1189227_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_191_1191057_qa_4/environment/Dockerfile b/tasks/0001_191_1191057_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_191_1191057_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_191_1191057_qa_4/environment/pull_bucket.py b/tasks/0001_191_1191057_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_191_1191057_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_191_1191057_qa_4/tests/grader.py b/tasks/0001_191_1191057_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_191_1191057_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_191_1191057_qa_4/tests/test.sh b/tasks/0001_191_1191057_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_191_1191057_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_243_1243037_qa_2/environment/Dockerfile b/tasks/0001_243_1243037_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_243_1243037_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_243_1243037_qa_2/environment/pull_bucket.py b/tasks/0001_243_1243037_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_243_1243037_qa_2/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0001_243_1243037_qa_2/tests/grader.py b/tasks/0001_243_1243037_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_243_1243037_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/0001_243_1243037_qa_2/tests/test.sh b/tasks/0001_243_1243037_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_243_1243037_qa_2/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0001_257_1257756_qa_3/environment/Dockerfile b/tasks/0001_257_1257756_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_257_1257756_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_257_1257756_qa_3/environment/pull_bucket.py b/tasks/0001_257_1257756_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_257_1257756_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_257_1257756_qa_3/tests/grader.py b/tasks/0001_257_1257756_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_257_1257756_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_257_1257756_qa_3/tests/test.sh b/tasks/0001_257_1257756_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_257_1257756_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_341_1341821_qa_1/environment/Dockerfile b/tasks/0001_341_1341821_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_341_1341821_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_341_1341821_qa_1/environment/pull_bucket.py b/tasks/0001_341_1341821_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_341_1341821_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_341_1341821_qa_1/tests/grader.py b/tasks/0001_341_1341821_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_341_1341821_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_341_1341821_qa_1/tests/test.sh b/tasks/0001_341_1341821_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_341_1341821_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_473_1473187_qa_1/environment/Dockerfile b/tasks/0001_473_1473187_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_473_1473187_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_473_1473187_qa_1/environment/pull_bucket.py b/tasks/0001_473_1473187_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_473_1473187_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_473_1473187_qa_1/tests/grader.py b/tasks/0001_473_1473187_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_473_1473187_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_473_1473187_qa_1/tests/test.sh b/tasks/0001_473_1473187_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_473_1473187_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_521_1521206_qa_2/environment/Dockerfile b/tasks/0001_521_1521206_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_521_1521206_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_521_1521206_qa_2/environment/pull_bucket.py b/tasks/0001_521_1521206_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_521_1521206_qa_2/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0001_521_1521206_qa_2/tests/grader.py b/tasks/0001_521_1521206_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_521_1521206_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/0001_521_1521206_qa_2/tests/test.sh b/tasks/0001_521_1521206_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_521_1521206_qa_2/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0001_522_1522371_qa_5/environment/Dockerfile b/tasks/0001_522_1522371_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_522_1522371_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_522_1522371_qa_5/environment/pull_bucket.py b/tasks/0001_522_1522371_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_522_1522371_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_522_1522371_qa_5/tests/grader.py b/tasks/0001_522_1522371_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_522_1522371_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_522_1522371_qa_5/tests/test.sh b/tasks/0001_522_1522371_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_522_1522371_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_541_1541002_qa_2/environment/Dockerfile b/tasks/0001_541_1541002_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_541_1541002_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_541_1541002_qa_2/environment/pull_bucket.py b/tasks/0001_541_1541002_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_541_1541002_qa_2/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0001_541_1541002_qa_2/tests/grader.py b/tasks/0001_541_1541002_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_541_1541002_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/0001_541_1541002_qa_2/tests/test.sh b/tasks/0001_541_1541002_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_541_1541002_qa_2/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0001_541_1541002_qa_4/environment/Dockerfile b/tasks/0001_541_1541002_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_541_1541002_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_541_1541002_qa_4/environment/pull_bucket.py b/tasks/0001_541_1541002_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_541_1541002_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_541_1541002_qa_4/tests/grader.py b/tasks/0001_541_1541002_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_541_1541002_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_541_1541002_qa_4/tests/test.sh b/tasks/0001_541_1541002_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_541_1541002_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_574_1574525_qa_2/environment/Dockerfile b/tasks/0001_574_1574525_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_574_1574525_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_574_1574525_qa_2/environment/pull_bucket.py b/tasks/0001_574_1574525_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_574_1574525_qa_2/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0001_574_1574525_qa_2/tests/grader.py b/tasks/0001_574_1574525_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_574_1574525_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/0001_574_1574525_qa_2/tests/test.sh b/tasks/0001_574_1574525_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_574_1574525_qa_2/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0001_583_1583897_qa_5/environment/Dockerfile b/tasks/0001_583_1583897_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_583_1583897_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_583_1583897_qa_5/environment/pull_bucket.py b/tasks/0001_583_1583897_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_583_1583897_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_583_1583897_qa_5/tests/grader.py b/tasks/0001_583_1583897_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_583_1583897_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_583_1583897_qa_5/tests/test.sh b/tasks/0001_583_1583897_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_583_1583897_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_637_1637985_qa_3/environment/Dockerfile b/tasks/0001_637_1637985_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_637_1637985_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_637_1637985_qa_3/environment/pull_bucket.py b/tasks/0001_637_1637985_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_637_1637985_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_637_1637985_qa_3/tests/grader.py b/tasks/0001_637_1637985_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_637_1637985_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_637_1637985_qa_3/tests/test.sh b/tasks/0001_637_1637985_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_637_1637985_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_666_1666101_qa_2/environment/Dockerfile b/tasks/0001_666_1666101_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_666_1666101_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_666_1666101_qa_2/environment/pull_bucket.py b/tasks/0001_666_1666101_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_666_1666101_qa_2/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0001_666_1666101_qa_2/tests/grader.py b/tasks/0001_666_1666101_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_666_1666101_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/0001_666_1666101_qa_2/tests/test.sh b/tasks/0001_666_1666101_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_666_1666101_qa_2/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0001_959_1959663_qa_3/environment/Dockerfile b/tasks/0001_959_1959663_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_959_1959663_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_959_1959663_qa_3/environment/pull_bucket.py b/tasks/0001_959_1959663_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_959_1959663_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_959_1959663_qa_3/tests/grader.py b/tasks/0001_959_1959663_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_959_1959663_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_959_1959663_qa_3/tests/test.sh b/tasks/0001_959_1959663_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_959_1959663_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_990_1990392_qa_4/environment/Dockerfile b/tasks/0001_990_1990392_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_990_1990392_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_990_1990392_qa_4/environment/pull_bucket.py b/tasks/0001_990_1990392_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_990_1990392_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_990_1990392_qa_4/tests/grader.py b/tasks/0001_990_1990392_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_990_1990392_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_990_1990392_qa_4/tests/test.sh b/tasks/0001_990_1990392_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_990_1990392_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/0002_158_2158528_qa_4/environment/Dockerfile b/tasks/0002_158_2158528_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0002_158_2158528_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0002_158_2158528_qa_4/environment/pull_bucket.py b/tasks/0002_158_2158528_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0002_158_2158528_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/0002_158_2158528_qa_4/tests/grader.py b/tasks/0002_158_2158528_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0002_158_2158528_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/0002_158_2158528_qa_4/tests/test.sh b/tasks/0002_158_2158528_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0002_158_2158528_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/0010_908_10908139_qa_1/environment/Dockerfile b/tasks/0010_908_10908139_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0010_908_10908139_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0010_908_10908139_qa_1/environment/pull_bucket.py b/tasks/0010_908_10908139_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0010_908_10908139_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/0010_908_10908139_qa_1/tests/grader.py b/tasks/0010_908_10908139_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0010_908_10908139_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/0010_908_10908139_qa_1/tests/test.sh b/tasks/0010_908_10908139_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0010_908_10908139_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/0010_909_10909980_qa_3/environment/Dockerfile b/tasks/0010_909_10909980_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0010_909_10909980_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0010_909_10909980_qa_3/environment/pull_bucket.py b/tasks/0010_909_10909980_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0010_909_10909980_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/0010_909_10909980_qa_3/tests/grader.py b/tasks/0010_909_10909980_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0010_909_10909980_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/0010_909_10909980_qa_3/tests/test.sh b/tasks/0010_909_10909980_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0010_909_10909980_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/0011_121_11121152_qa_3/environment/Dockerfile b/tasks/0011_121_11121152_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0011_121_11121152_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0011_121_11121152_qa_3/environment/pull_bucket.py b/tasks/0011_121_11121152_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0011_121_11121152_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/0011_121_11121152_qa_3/tests/grader.py b/tasks/0011_121_11121152_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0011_121_11121152_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/0011_121_11121152_qa_3/tests/test.sh b/tasks/0011_121_11121152_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0011_121_11121152_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/0011_587_11587305_qa_5/environment/Dockerfile b/tasks/0011_587_11587305_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0011_587_11587305_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0011_587_11587305_qa_5/environment/pull_bucket.py b/tasks/0011_587_11587305_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0011_587_11587305_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/0011_587_11587305_qa_5/tests/grader.py b/tasks/0011_587_11587305_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0011_587_11587305_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/0011_587_11587305_qa_5/tests/test.sh b/tasks/0011_587_11587305_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0011_587_11587305_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/0011_970_11970593_qa_2/environment/Dockerfile b/tasks/0011_970_11970593_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0011_970_11970593_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0011_970_11970593_qa_2/environment/pull_bucket.py b/tasks/0011_970_11970593_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0011_970_11970593_qa_2/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0011_970_11970593_qa_2/tests/grader.py b/tasks/0011_970_11970593_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0011_970_11970593_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/0011_970_11970593_qa_2/tests/test.sh b/tasks/0011_970_11970593_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0011_970_11970593_qa_2/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0012_161_12161282_qa_4/environment/Dockerfile b/tasks/0012_161_12161282_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0012_161_12161282_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0012_161_12161282_qa_4/environment/pull_bucket.py b/tasks/0012_161_12161282_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0012_161_12161282_qa_4/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0012_161_12161282_qa_4/tests/grader.py b/tasks/0012_161_12161282_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0012_161_12161282_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/0012_161_12161282_qa_4/tests/test.sh b/tasks/0012_161_12161282_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0012_161_12161282_qa_4/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0012_692_12692192_qa_3/environment/Dockerfile b/tasks/0012_692_12692192_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0012_692_12692192_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0012_692_12692192_qa_3/environment/pull_bucket.py b/tasks/0012_692_12692192_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0012_692_12692192_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/0012_692_12692192_qa_3/tests/grader.py b/tasks/0012_692_12692192_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0012_692_12692192_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/0012_692_12692192_qa_3/tests/test.sh b/tasks/0012_692_12692192_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0012_692_12692192_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/0012_941_12941575_qa_2/environment/Dockerfile b/tasks/0012_941_12941575_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0012_941_12941575_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0012_941_12941575_qa_2/environment/pull_bucket.py b/tasks/0012_941_12941575_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0012_941_12941575_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/0012_941_12941575_qa_2/tests/grader.py b/tasks/0012_941_12941575_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0012_941_12941575_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/0012_941_12941575_qa_2/tests/test.sh b/tasks/0012_941_12941575_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0012_941_12941575_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/0013_169_13169934_qa_5/environment/Dockerfile b/tasks/0013_169_13169934_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0013_169_13169934_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0013_169_13169934_qa_5/environment/pull_bucket.py b/tasks/0013_169_13169934_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0013_169_13169934_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/0013_169_13169934_qa_5/tests/grader.py b/tasks/0013_169_13169934_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0013_169_13169934_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/0013_169_13169934_qa_5/tests/test.sh b/tasks/0013_169_13169934_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0013_169_13169934_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/0013_604_13604091_qa_2/environment/Dockerfile b/tasks/0013_604_13604091_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0013_604_13604091_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0013_604_13604091_qa_2/environment/pull_bucket.py b/tasks/0013_604_13604091_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0013_604_13604091_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/0013_604_13604091_qa_2/tests/grader.py b/tasks/0013_604_13604091_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0013_604_13604091_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/0013_604_13604091_qa_2/tests/test.sh b/tasks/0013_604_13604091_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0013_604_13604091_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/0013_613_13613426_qa_5/environment/Dockerfile b/tasks/0013_613_13613426_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0013_613_13613426_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0013_613_13613426_qa_5/environment/pull_bucket.py b/tasks/0013_613_13613426_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0013_613_13613426_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/0013_613_13613426_qa_5/tests/grader.py b/tasks/0013_613_13613426_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0013_613_13613426_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/0013_613_13613426_qa_5/tests/test.sh b/tasks/0013_613_13613426_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0013_613_13613426_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/0013_733_13733964_qa_1/environment/Dockerfile b/tasks/0013_733_13733964_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0013_733_13733964_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0013_733_13733964_qa_1/environment/pull_bucket.py b/tasks/0013_733_13733964_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0013_733_13733964_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/0013_733_13733964_qa_1/tests/grader.py b/tasks/0013_733_13733964_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0013_733_13733964_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/0013_733_13733964_qa_1/tests/test.sh b/tasks/0013_733_13733964_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0013_733_13733964_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/0013_839_13839617_qa_5/environment/Dockerfile b/tasks/0013_839_13839617_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0013_839_13839617_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0013_839_13839617_qa_5/environment/pull_bucket.py b/tasks/0013_839_13839617_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0013_839_13839617_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/0013_839_13839617_qa_5/tests/grader.py b/tasks/0013_839_13839617_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0013_839_13839617_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/0013_839_13839617_qa_5/tests/test.sh b/tasks/0013_839_13839617_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0013_839_13839617_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/0014_390_14390255_qa_4/environment/Dockerfile b/tasks/0014_390_14390255_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0014_390_14390255_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0014_390_14390255_qa_4/environment/pull_bucket.py b/tasks/0014_390_14390255_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0014_390_14390255_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/0014_390_14390255_qa_4/tests/grader.py b/tasks/0014_390_14390255_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0014_390_14390255_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/0014_390_14390255_qa_4/tests/test.sh b/tasks/0014_390_14390255_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0014_390_14390255_qa_4/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0014_428_14428721_qa_1/environment/Dockerfile b/tasks/0014_428_14428721_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0014_428_14428721_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0014_428_14428721_qa_1/environment/pull_bucket.py b/tasks/0014_428_14428721_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0014_428_14428721_qa_1/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0014_428_14428721_qa_1/tests/grader.py b/tasks/0014_428_14428721_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0014_428_14428721_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/0014_428_14428721_qa_1/tests/test.sh b/tasks/0014_428_14428721_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0014_428_14428721_qa_1/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0014_469_14469283_qa_3/environment/Dockerfile b/tasks/0014_469_14469283_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0014_469_14469283_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0014_469_14469283_qa_3/environment/pull_bucket.py b/tasks/0014_469_14469283_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0014_469_14469283_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/0014_469_14469283_qa_3/tests/grader.py b/tasks/0014_469_14469283_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0014_469_14469283_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/0014_469_14469283_qa_3/tests/test.sh b/tasks/0014_469_14469283_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0014_469_14469283_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/0014_469_14469283_qa_4/environment/Dockerfile b/tasks/0014_469_14469283_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0014_469_14469283_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0014_469_14469283_qa_4/environment/pull_bucket.py b/tasks/0014_469_14469283_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0014_469_14469283_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/0014_469_14469283_qa_4/tests/grader.py b/tasks/0014_469_14469283_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0014_469_14469283_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/0014_469_14469283_qa_4/tests/test.sh b/tasks/0014_469_14469283_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0014_469_14469283_qa_4/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0014_933_14933483_qa_2/environment/Dockerfile b/tasks/0014_933_14933483_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0014_933_14933483_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0014_933_14933483_qa_2/environment/pull_bucket.py b/tasks/0014_933_14933483_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0014_933_14933483_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/0014_933_14933483_qa_2/tests/grader.py b/tasks/0014_933_14933483_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0014_933_14933483_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/0014_933_14933483_qa_2/tests/test.sh b/tasks/0014_933_14933483_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0014_933_14933483_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/0016_136_16136283_qa_1/environment/Dockerfile b/tasks/0016_136_16136283_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0016_136_16136283_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0016_136_16136283_qa_1/environment/pull_bucket.py b/tasks/0016_136_16136283_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0016_136_16136283_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/0016_136_16136283_qa_1/tests/grader.py b/tasks/0016_136_16136283_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0016_136_16136283_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/0016_136_16136283_qa_1/tests/test.sh b/tasks/0016_136_16136283_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0016_136_16136283_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/0016_985_16985676_qa_3/environment/Dockerfile b/tasks/0016_985_16985676_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0016_985_16985676_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0016_985_16985676_qa_3/environment/pull_bucket.py b/tasks/0016_985_16985676_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0016_985_16985676_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/0016_985_16985676_qa_3/tests/grader.py b/tasks/0016_985_16985676_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0016_985_16985676_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/0016_985_16985676_qa_3/tests/test.sh b/tasks/0016_985_16985676_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0016_985_16985676_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/0018_038_18038519_qa_5/environment/Dockerfile b/tasks/0018_038_18038519_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0018_038_18038519_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0018_038_18038519_qa_5/environment/pull_bucket.py b/tasks/0018_038_18038519_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0018_038_18038519_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/0018_038_18038519_qa_5/tests/grader.py b/tasks/0018_038_18038519_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0018_038_18038519_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/0018_038_18038519_qa_5/tests/test.sh b/tasks/0018_038_18038519_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0018_038_18038519_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/0018_456_18456045_qa_5/environment/Dockerfile b/tasks/0018_456_18456045_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0018_456_18456045_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0018_456_18456045_qa_5/environment/pull_bucket.py b/tasks/0018_456_18456045_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0018_456_18456045_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/0018_456_18456045_qa_5/tests/grader.py b/tasks/0018_456_18456045_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0018_456_18456045_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/0018_456_18456045_qa_5/tests/test.sh b/tasks/0018_456_18456045_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0018_456_18456045_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_299_21299002_qa_3/environment/Dockerfile b/tasks/0021_299_21299002_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0021_299_21299002_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0021_299_21299002_qa_3/environment/pull_bucket.py b/tasks/0021_299_21299002_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0021_299_21299002_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_299_21299002_qa_3/tests/grader.py b/tasks/0021_299_21299002_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0021_299_21299002_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_299_21299002_qa_3/tests/test.sh b/tasks/0021_299_21299002_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0021_299_21299002_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_353_21353656_qa_1/environment/Dockerfile b/tasks/0021_353_21353656_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0021_353_21353656_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0021_353_21353656_qa_1/environment/pull_bucket.py b/tasks/0021_353_21353656_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0021_353_21353656_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/0021_353_21353656_qa_1/tests/grader.py b/tasks/0021_353_21353656_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0021_353_21353656_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/0021_353_21353656_qa_1/tests/test.sh b/tasks/0021_353_21353656_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0021_353_21353656_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/0022_886_22886038_qa_4/environment/Dockerfile b/tasks/0022_886_22886038_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0022_886_22886038_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0022_886_22886038_qa_4/environment/pull_bucket.py b/tasks/0022_886_22886038_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0022_886_22886038_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/0022_886_22886038_qa_4/tests/grader.py b/tasks/0022_886_22886038_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0022_886_22886038_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/0022_886_22886038_qa_4/tests/test.sh b/tasks/0022_886_22886038_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0022_886_22886038_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/0022_916_22916338_qa_5/environment/Dockerfile b/tasks/0022_916_22916338_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0022_916_22916338_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0022_916_22916338_qa_5/environment/pull_bucket.py b/tasks/0022_916_22916338_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0022_916_22916338_qa_5/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0022_916_22916338_qa_5/tests/grader.py b/tasks/0022_916_22916338_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0022_916_22916338_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/0022_916_22916338_qa_5/tests/test.sh b/tasks/0022_916_22916338_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0022_916_22916338_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_583_23583710_qa_4/environment/Dockerfile b/tasks/0023_583_23583710_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0023_583_23583710_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0023_583_23583710_qa_4/environment/pull_bucket.py b/tasks/0023_583_23583710_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0023_583_23583710_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/0023_583_23583710_qa_4/tests/grader.py b/tasks/0023_583_23583710_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0023_583_23583710_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/0023_583_23583710_qa_4/tests/test.sh b/tasks/0023_583_23583710_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0023_583_23583710_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/0023_598_23598239_qa_1/environment/Dockerfile b/tasks/0023_598_23598239_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0023_598_23598239_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0023_598_23598239_qa_1/environment/pull_bucket.py b/tasks/0023_598_23598239_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0023_598_23598239_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/0023_598_23598239_qa_1/tests/grader.py b/tasks/0023_598_23598239_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0023_598_23598239_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/0023_598_23598239_qa_1/tests/test.sh b/tasks/0023_598_23598239_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0023_598_23598239_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/0024_315_24315892_qa_3/environment/Dockerfile b/tasks/0024_315_24315892_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0024_315_24315892_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0024_315_24315892_qa_3/environment/pull_bucket.py b/tasks/0024_315_24315892_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0024_315_24315892_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/0024_315_24315892_qa_3/tests/grader.py b/tasks/0024_315_24315892_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0024_315_24315892_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/0024_315_24315892_qa_3/tests/test.sh b/tasks/0024_315_24315892_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0024_315_24315892_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/0025_274_25274016_qa_4/environment/Dockerfile b/tasks/0025_274_25274016_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0025_274_25274016_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0025_274_25274016_qa_4/environment/pull_bucket.py b/tasks/0025_274_25274016_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0025_274_25274016_qa_4/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0025_274_25274016_qa_4/tests/grader.py b/tasks/0025_274_25274016_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0025_274_25274016_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/0025_274_25274016_qa_4/tests/test.sh b/tasks/0025_274_25274016_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0025_274_25274016_qa_4/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0026_836_26836336_qa_1/environment/Dockerfile b/tasks/0026_836_26836336_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0026_836_26836336_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0026_836_26836336_qa_1/environment/pull_bucket.py b/tasks/0026_836_26836336_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0026_836_26836336_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/0026_836_26836336_qa_1/tests/grader.py b/tasks/0026_836_26836336_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0026_836_26836336_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/0026_836_26836336_qa_1/tests/test.sh b/tasks/0026_836_26836336_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0026_836_26836336_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/0028_299_28299086_qa_3/environment/Dockerfile b/tasks/0028_299_28299086_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0028_299_28299086_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0028_299_28299086_qa_3/environment/pull_bucket.py b/tasks/0028_299_28299086_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0028_299_28299086_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/0028_299_28299086_qa_3/tests/grader.py b/tasks/0028_299_28299086_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0028_299_28299086_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/0028_299_28299086_qa_3/tests/test.sh b/tasks/0028_299_28299086_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0028_299_28299086_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/0028_443_28443310_qa_4/environment/Dockerfile b/tasks/0028_443_28443310_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0028_443_28443310_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0028_443_28443310_qa_4/environment/pull_bucket.py b/tasks/0028_443_28443310_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0028_443_28443310_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/0028_443_28443310_qa_4/tests/grader.py b/tasks/0028_443_28443310_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0028_443_28443310_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/0028_443_28443310_qa_4/tests/test.sh b/tasks/0028_443_28443310_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0028_443_28443310_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/0029_108_29108182_qa_1/environment/Dockerfile b/tasks/0029_108_29108182_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0029_108_29108182_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0029_108_29108182_qa_1/environment/pull_bucket.py b/tasks/0029_108_29108182_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0029_108_29108182_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/0029_108_29108182_qa_1/tests/grader.py b/tasks/0029_108_29108182_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0029_108_29108182_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/0029_108_29108182_qa_1/tests/test.sh b/tasks/0029_108_29108182_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0029_108_29108182_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/0029_204_29204719_qa_2/environment/Dockerfile b/tasks/0029_204_29204719_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0029_204_29204719_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0029_204_29204719_qa_2/environment/pull_bucket.py b/tasks/0029_204_29204719_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0029_204_29204719_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/0029_204_29204719_qa_2/tests/grader.py b/tasks/0029_204_29204719_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0029_204_29204719_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/0029_204_29204719_qa_2/tests/test.sh b/tasks/0029_204_29204719_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0029_204_29204719_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/0029_784_29784165_qa_1/environment/Dockerfile b/tasks/0029_784_29784165_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0029_784_29784165_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0029_784_29784165_qa_1/environment/pull_bucket.py b/tasks/0029_784_29784165_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0029_784_29784165_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/0029_784_29784165_qa_1/tests/grader.py b/tasks/0029_784_29784165_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0029_784_29784165_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/0029_784_29784165_qa_1/tests/test.sh b/tasks/0029_784_29784165_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0029_784_29784165_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/0030_348_30348412_qa_2/environment/Dockerfile b/tasks/0030_348_30348412_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0030_348_30348412_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0030_348_30348412_qa_2/environment/pull_bucket.py b/tasks/0030_348_30348412_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0030_348_30348412_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/0030_348_30348412_qa_2/tests/grader.py b/tasks/0030_348_30348412_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0030_348_30348412_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/0030_348_30348412_qa_2/tests/test.sh b/tasks/0030_348_30348412_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0030_348_30348412_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/0030_804_30804903_qa_1/environment/Dockerfile b/tasks/0030_804_30804903_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0030_804_30804903_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0030_804_30804903_qa_1/environment/pull_bucket.py b/tasks/0030_804_30804903_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0030_804_30804903_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/0030_804_30804903_qa_1/tests/grader.py b/tasks/0030_804_30804903_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0030_804_30804903_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/0030_804_30804903_qa_1/tests/test.sh b/tasks/0030_804_30804903_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0030_804_30804903_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/0030_817_30817038_qa_2/environment/Dockerfile b/tasks/0030_817_30817038_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0030_817_30817038_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0030_817_30817038_qa_2/environment/pull_bucket.py b/tasks/0030_817_30817038_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0030_817_30817038_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/0030_817_30817038_qa_2/tests/grader.py b/tasks/0030_817_30817038_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0030_817_30817038_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/0030_817_30817038_qa_2/tests/test.sh b/tasks/0030_817_30817038_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0030_817_30817038_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/0030_890_30890976_qa_5/environment/Dockerfile b/tasks/0030_890_30890976_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0030_890_30890976_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0030_890_30890976_qa_5/environment/pull_bucket.py b/tasks/0030_890_30890976_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0030_890_30890976_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/0030_890_30890976_qa_5/tests/grader.py b/tasks/0030_890_30890976_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0030_890_30890976_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/0030_890_30890976_qa_5/tests/test.sh b/tasks/0030_890_30890976_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0030_890_30890976_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/0031_089_31089222_qa_2/environment/Dockerfile b/tasks/0031_089_31089222_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0031_089_31089222_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0031_089_31089222_qa_2/environment/pull_bucket.py b/tasks/0031_089_31089222_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0031_089_31089222_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/0031_089_31089222_qa_2/tests/grader.py b/tasks/0031_089_31089222_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0031_089_31089222_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/0031_089_31089222_qa_2/tests/test.sh b/tasks/0031_089_31089222_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0031_089_31089222_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/0031_987_31987709_qa_1/environment/Dockerfile b/tasks/0031_987_31987709_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0031_987_31987709_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0031_987_31987709_qa_1/environment/pull_bucket.py b/tasks/0031_987_31987709_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0031_987_31987709_qa_1/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0031_987_31987709_qa_1/tests/grader.py b/tasks/0031_987_31987709_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0031_987_31987709_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/0031_987_31987709_qa_1/tests/test.sh b/tasks/0031_987_31987709_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0031_987_31987709_qa_1/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0032_101_32101676_qa_2/environment/Dockerfile b/tasks/0032_101_32101676_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0032_101_32101676_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0032_101_32101676_qa_2/environment/pull_bucket.py b/tasks/0032_101_32101676_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0032_101_32101676_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/0032_101_32101676_qa_2/tests/grader.py b/tasks/0032_101_32101676_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0032_101_32101676_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/0032_101_32101676_qa_2/tests/test.sh b/tasks/0032_101_32101676_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0032_101_32101676_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/0032_314_32314190_qa_4/environment/Dockerfile b/tasks/0032_314_32314190_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0032_314_32314190_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0032_314_32314190_qa_4/environment/pull_bucket.py b/tasks/0032_314_32314190_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0032_314_32314190_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/0032_314_32314190_qa_4/tests/grader.py b/tasks/0032_314_32314190_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0032_314_32314190_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/0032_314_32314190_qa_4/tests/test.sh b/tasks/0032_314_32314190_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0032_314_32314190_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/0032_386_32386426_qa_2/environment/Dockerfile b/tasks/0032_386_32386426_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0032_386_32386426_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0032_386_32386426_qa_2/environment/pull_bucket.py b/tasks/0032_386_32386426_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0032_386_32386426_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/0032_386_32386426_qa_2/tests/grader.py b/tasks/0032_386_32386426_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0032_386_32386426_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/0032_386_32386426_qa_2/tests/test.sh b/tasks/0032_386_32386426_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0032_386_32386426_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/0033_684_33684962_qa_3/environment/Dockerfile b/tasks/0033_684_33684962_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0033_684_33684962_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0033_684_33684962_qa_3/environment/pull_bucket.py b/tasks/0033_684_33684962_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0033_684_33684962_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_684_33684962_qa_3/tests/grader.py b/tasks/0033_684_33684962_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0033_684_33684962_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_684_33684962_qa_3/tests/test.sh b/tasks/0033_684_33684962_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0033_684_33684962_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/0033_787_33787812_qa_1/environment/Dockerfile b/tasks/0033_787_33787812_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0033_787_33787812_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0033_787_33787812_qa_1/environment/pull_bucket.py b/tasks/0033_787_33787812_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0033_787_33787812_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/0033_787_33787812_qa_1/tests/grader.py b/tasks/0033_787_33787812_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0033_787_33787812_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/0033_787_33787812_qa_1/tests/test.sh b/tasks/0033_787_33787812_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0033_787_33787812_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/0034_170_34170800_qa_2/environment/Dockerfile b/tasks/0034_170_34170800_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0034_170_34170800_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0034_170_34170800_qa_2/environment/pull_bucket.py b/tasks/0034_170_34170800_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0034_170_34170800_qa_2/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0034_170_34170800_qa_2/tests/grader.py b/tasks/0034_170_34170800_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0034_170_34170800_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/0034_170_34170800_qa_2/tests/test.sh b/tasks/0034_170_34170800_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0034_170_34170800_qa_2/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0034_339_34339717_qa_5/environment/Dockerfile b/tasks/0034_339_34339717_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0034_339_34339717_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0034_339_34339717_qa_5/environment/pull_bucket.py b/tasks/0034_339_34339717_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0034_339_34339717_qa_5/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0034_339_34339717_qa_5/tests/grader.py b/tasks/0034_339_34339717_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0034_339_34339717_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/0034_339_34339717_qa_5/tests/test.sh b/tasks/0034_339_34339717_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0034_339_34339717_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/0034_748_34748003_qa_1/environment/Dockerfile b/tasks/0034_748_34748003_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0034_748_34748003_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0034_748_34748003_qa_1/environment/pull_bucket.py b/tasks/0034_748_34748003_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0034_748_34748003_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/0034_748_34748003_qa_1/tests/grader.py b/tasks/0034_748_34748003_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0034_748_34748003_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/0034_748_34748003_qa_1/tests/test.sh b/tasks/0034_748_34748003_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0034_748_34748003_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/0034_912_34912092_qa_3/environment/Dockerfile b/tasks/0034_912_34912092_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0034_912_34912092_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0034_912_34912092_qa_3/environment/pull_bucket.py b/tasks/0034_912_34912092_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0034_912_34912092_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/0034_912_34912092_qa_3/tests/grader.py b/tasks/0034_912_34912092_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0034_912_34912092_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/0034_912_34912092_qa_3/tests/test.sh b/tasks/0034_912_34912092_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0034_912_34912092_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/0034_912_34912092_qa_5/environment/Dockerfile b/tasks/0034_912_34912092_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0034_912_34912092_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0034_912_34912092_qa_5/environment/pull_bucket.py b/tasks/0034_912_34912092_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0034_912_34912092_qa_5/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0034_912_34912092_qa_5/tests/grader.py b/tasks/0034_912_34912092_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0034_912_34912092_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/0034_912_34912092_qa_5/tests/test.sh b/tasks/0034_912_34912092_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0034_912_34912092_qa_5/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0035_171_35171975_qa_4/environment/Dockerfile b/tasks/0035_171_35171975_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0035_171_35171975_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0035_171_35171975_qa_4/environment/pull_bucket.py b/tasks/0035_171_35171975_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0035_171_35171975_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/0035_171_35171975_qa_4/tests/grader.py b/tasks/0035_171_35171975_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0035_171_35171975_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/0035_171_35171975_qa_4/tests/test.sh b/tasks/0035_171_35171975_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0035_171_35171975_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/0035_236_35236553_qa_4/environment/Dockerfile b/tasks/0035_236_35236553_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0035_236_35236553_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0035_236_35236553_qa_4/environment/pull_bucket.py b/tasks/0035_236_35236553_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0035_236_35236553_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/0035_236_35236553_qa_4/tests/grader.py b/tasks/0035_236_35236553_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0035_236_35236553_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/0035_236_35236553_qa_4/tests/test.sh b/tasks/0035_236_35236553_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0035_236_35236553_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/0036_284_36284344_qa_5/environment/Dockerfile b/tasks/0036_284_36284344_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0036_284_36284344_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0036_284_36284344_qa_5/environment/pull_bucket.py b/tasks/0036_284_36284344_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0036_284_36284344_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/0036_284_36284344_qa_5/tests/grader.py b/tasks/0036_284_36284344_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0036_284_36284344_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/0036_284_36284344_qa_5/tests/test.sh b/tasks/0036_284_36284344_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0036_284_36284344_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/0036_436_36436182_qa_5/environment/Dockerfile b/tasks/0036_436_36436182_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0036_436_36436182_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0036_436_36436182_qa_5/environment/pull_bucket.py b/tasks/0036_436_36436182_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0036_436_36436182_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/0036_436_36436182_qa_5/tests/grader.py b/tasks/0036_436_36436182_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0036_436_36436182_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/0036_436_36436182_qa_5/tests/test.sh b/tasks/0036_436_36436182_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0036_436_36436182_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/0036_916_36916974_qa_1/environment/Dockerfile b/tasks/0036_916_36916974_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0036_916_36916974_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0036_916_36916974_qa_1/environment/pull_bucket.py b/tasks/0036_916_36916974_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0036_916_36916974_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/0036_916_36916974_qa_1/tests/grader.py b/tasks/0036_916_36916974_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0036_916_36916974_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/0036_916_36916974_qa_1/tests/test.sh b/tasks/0036_916_36916974_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0036_916_36916974_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/0036_927_36927955_qa_1/environment/Dockerfile b/tasks/0036_927_36927955_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0036_927_36927955_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0036_927_36927955_qa_1/environment/pull_bucket.py b/tasks/0036_927_36927955_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0036_927_36927955_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/0036_927_36927955_qa_1/tests/grader.py b/tasks/0036_927_36927955_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0036_927_36927955_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/0036_927_36927955_qa_1/tests/test.sh b/tasks/0036_927_36927955_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0036_927_36927955_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/0038_970_38970193_qa_5/environment/Dockerfile b/tasks/0038_970_38970193_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0038_970_38970193_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0038_970_38970193_qa_5/environment/pull_bucket.py b/tasks/0038_970_38970193_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0038_970_38970193_qa_5/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0038_970_38970193_qa_5/tests/grader.py b/tasks/0038_970_38970193_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0038_970_38970193_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/0038_970_38970193_qa_5/tests/test.sh b/tasks/0038_970_38970193_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0038_970_38970193_qa_5/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0039_370_39370613_qa_3/environment/Dockerfile b/tasks/0039_370_39370613_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0039_370_39370613_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0039_370_39370613_qa_3/environment/pull_bucket.py b/tasks/0039_370_39370613_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0039_370_39370613_qa_3/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0039_370_39370613_qa_3/tests/grader.py b/tasks/0039_370_39370613_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0039_370_39370613_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/0039_370_39370613_qa_3/tests/test.sh b/tasks/0039_370_39370613_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0039_370_39370613_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_409_39409376_qa_2/environment/Dockerfile b/tasks/0039_409_39409376_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0039_409_39409376_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0039_409_39409376_qa_2/environment/pull_bucket.py b/tasks/0039_409_39409376_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0039_409_39409376_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/0039_409_39409376_qa_2/tests/grader.py b/tasks/0039_409_39409376_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0039_409_39409376_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/0039_409_39409376_qa_2/tests/test.sh b/tasks/0039_409_39409376_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0039_409_39409376_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/0039_512_39512601_qa_2/environment/Dockerfile b/tasks/0039_512_39512601_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0039_512_39512601_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0039_512_39512601_qa_2/environment/pull_bucket.py b/tasks/0039_512_39512601_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0039_512_39512601_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/0039_512_39512601_qa_2/tests/grader.py b/tasks/0039_512_39512601_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0039_512_39512601_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/0039_512_39512601_qa_2/tests/test.sh b/tasks/0039_512_39512601_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0039_512_39512601_qa_2/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0040_738_40738491_qa_3/environment/Dockerfile b/tasks/0040_738_40738491_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0040_738_40738491_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0040_738_40738491_qa_3/environment/pull_bucket.py b/tasks/0040_738_40738491_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0040_738_40738491_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_738_40738491_qa_3/tests/grader.py b/tasks/0040_738_40738491_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0040_738_40738491_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_738_40738491_qa_3/tests/test.sh b/tasks/0040_738_40738491_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0040_738_40738491_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_738_40738491_qa_4/environment/Dockerfile b/tasks/0040_738_40738491_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0040_738_40738491_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0040_738_40738491_qa_4/environment/pull_bucket.py b/tasks/0040_738_40738491_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0040_738_40738491_qa_4/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0040_738_40738491_qa_4/tests/grader.py b/tasks/0040_738_40738491_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0040_738_40738491_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/0040_738_40738491_qa_4/tests/test.sh b/tasks/0040_738_40738491_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0040_738_40738491_qa_4/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0041_015_41015677_qa_4/environment/Dockerfile b/tasks/0041_015_41015677_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0041_015_41015677_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0041_015_41015677_qa_4/environment/pull_bucket.py b/tasks/0041_015_41015677_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0041_015_41015677_qa_4/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0041_015_41015677_qa_4/tests/grader.py b/tasks/0041_015_41015677_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0041_015_41015677_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/0041_015_41015677_qa_4/tests/test.sh b/tasks/0041_015_41015677_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0041_015_41015677_qa_4/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0041_214_41214331_qa_5/environment/Dockerfile b/tasks/0041_214_41214331_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0041_214_41214331_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0041_214_41214331_qa_5/environment/pull_bucket.py b/tasks/0041_214_41214331_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0041_214_41214331_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_214_41214331_qa_5/tests/grader.py b/tasks/0041_214_41214331_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0041_214_41214331_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_214_41214331_qa_5/tests/test.sh b/tasks/0041_214_41214331_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0041_214_41214331_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/0041_321_41321221_qa_2/environment/Dockerfile b/tasks/0041_321_41321221_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0041_321_41321221_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0041_321_41321221_qa_2/environment/pull_bucket.py b/tasks/0041_321_41321221_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0041_321_41321221_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/0041_321_41321221_qa_2/tests/grader.py b/tasks/0041_321_41321221_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0041_321_41321221_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/0041_321_41321221_qa_2/tests/test.sh b/tasks/0041_321_41321221_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0041_321_41321221_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/0041_323_41323136_qa_2/environment/Dockerfile b/tasks/0041_323_41323136_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0041_323_41323136_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0041_323_41323136_qa_2/environment/pull_bucket.py b/tasks/0041_323_41323136_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0041_323_41323136_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/0041_323_41323136_qa_2/tests/grader.py b/tasks/0041_323_41323136_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0041_323_41323136_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/0041_323_41323136_qa_2/tests/test.sh b/tasks/0041_323_41323136_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0041_323_41323136_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/0041_712_41712543_qa_1/environment/Dockerfile b/tasks/0041_712_41712543_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0041_712_41712543_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0041_712_41712543_qa_1/environment/pull_bucket.py b/tasks/0041_712_41712543_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0041_712_41712543_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/0041_712_41712543_qa_1/tests/grader.py b/tasks/0041_712_41712543_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0041_712_41712543_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/0041_712_41712543_qa_1/tests/test.sh b/tasks/0041_712_41712543_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0041_712_41712543_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/0042_372_42372757_qa_1/environment/Dockerfile b/tasks/0042_372_42372757_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0042_372_42372757_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0042_372_42372757_qa_1/environment/pull_bucket.py b/tasks/0042_372_42372757_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0042_372_42372757_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/0042_372_42372757_qa_1/tests/grader.py b/tasks/0042_372_42372757_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0042_372_42372757_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/0042_372_42372757_qa_1/tests/test.sh b/tasks/0042_372_42372757_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0042_372_42372757_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/0042_528_42528802_qa_3/environment/Dockerfile b/tasks/0042_528_42528802_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0042_528_42528802_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0042_528_42528802_qa_3/environment/pull_bucket.py b/tasks/0042_528_42528802_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0042_528_42528802_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/0042_528_42528802_qa_3/tests/grader.py b/tasks/0042_528_42528802_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0042_528_42528802_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/0042_528_42528802_qa_3/tests/test.sh b/tasks/0042_528_42528802_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0042_528_42528802_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/0042_773_42773926_qa_2/environment/Dockerfile b/tasks/0042_773_42773926_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0042_773_42773926_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0042_773_42773926_qa_2/environment/pull_bucket.py b/tasks/0042_773_42773926_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0042_773_42773926_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/0042_773_42773926_qa_2/tests/grader.py b/tasks/0042_773_42773926_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0042_773_42773926_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/0042_773_42773926_qa_2/tests/test.sh b/tasks/0042_773_42773926_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0042_773_42773926_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/0042_773_42773926_qa_3/environment/Dockerfile b/tasks/0042_773_42773926_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0042_773_42773926_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0042_773_42773926_qa_3/environment/pull_bucket.py b/tasks/0042_773_42773926_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0042_773_42773926_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/0042_773_42773926_qa_3/tests/grader.py b/tasks/0042_773_42773926_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0042_773_42773926_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/0042_773_42773926_qa_3/tests/test.sh b/tasks/0042_773_42773926_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0042_773_42773926_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/0042_991_42991381_qa_5/environment/Dockerfile b/tasks/0042_991_42991381_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0042_991_42991381_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0042_991_42991381_qa_5/environment/pull_bucket.py b/tasks/0042_991_42991381_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0042_991_42991381_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_991_42991381_qa_5/tests/grader.py b/tasks/0042_991_42991381_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0042_991_42991381_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_991_42991381_qa_5/tests/test.sh b/tasks/0042_991_42991381_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0042_991_42991381_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/0043_373_43373918_qa_4/environment/Dockerfile b/tasks/0043_373_43373918_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0043_373_43373918_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0043_373_43373918_qa_4/environment/pull_bucket.py b/tasks/0043_373_43373918_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0043_373_43373918_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/0043_373_43373918_qa_4/tests/grader.py b/tasks/0043_373_43373918_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0043_373_43373918_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/0043_373_43373918_qa_4/tests/test.sh b/tasks/0043_373_43373918_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0043_373_43373918_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/0043_774_43774308_qa_1/environment/Dockerfile b/tasks/0043_774_43774308_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0043_774_43774308_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0043_774_43774308_qa_1/environment/pull_bucket.py b/tasks/0043_774_43774308_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0043_774_43774308_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/0043_774_43774308_qa_1/tests/grader.py b/tasks/0043_774_43774308_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0043_774_43774308_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/0043_774_43774308_qa_1/tests/test.sh b/tasks/0043_774_43774308_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0043_774_43774308_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/0044_727_44727189_qa_1/environment/Dockerfile b/tasks/0044_727_44727189_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0044_727_44727189_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0044_727_44727189_qa_1/environment/pull_bucket.py b/tasks/0044_727_44727189_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0044_727_44727189_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/0044_727_44727189_qa_1/tests/grader.py b/tasks/0044_727_44727189_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0044_727_44727189_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/0044_727_44727189_qa_1/tests/test.sh b/tasks/0044_727_44727189_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0044_727_44727189_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/0045_821_45821165_qa_2/environment/Dockerfile b/tasks/0045_821_45821165_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0045_821_45821165_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0045_821_45821165_qa_2/environment/pull_bucket.py b/tasks/0045_821_45821165_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0045_821_45821165_qa_2/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0045_821_45821165_qa_2/tests/grader.py b/tasks/0045_821_45821165_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0045_821_45821165_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/0045_821_45821165_qa_2/tests/test.sh b/tasks/0045_821_45821165_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0045_821_45821165_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/0045_821_45821165_qa_3/environment/Dockerfile b/tasks/0045_821_45821165_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0045_821_45821165_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0045_821_45821165_qa_3/environment/pull_bucket.py b/tasks/0045_821_45821165_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0045_821_45821165_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/0045_821_45821165_qa_3/tests/grader.py b/tasks/0045_821_45821165_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0045_821_45821165_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/0045_821_45821165_qa_3/tests/test.sh b/tasks/0045_821_45821165_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0045_821_45821165_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/0045_969_45969290_qa_1/environment/Dockerfile b/tasks/0045_969_45969290_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0045_969_45969290_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0045_969_45969290_qa_1/environment/pull_bucket.py b/tasks/0045_969_45969290_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0045_969_45969290_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/0045_969_45969290_qa_1/tests/grader.py b/tasks/0045_969_45969290_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0045_969_45969290_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/0045_969_45969290_qa_1/tests/test.sh b/tasks/0045_969_45969290_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0045_969_45969290_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/0046_113_46113496_qa_1/environment/Dockerfile b/tasks/0046_113_46113496_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0046_113_46113496_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0046_113_46113496_qa_1/environment/pull_bucket.py b/tasks/0046_113_46113496_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0046_113_46113496_qa_1/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0046_113_46113496_qa_1/tests/grader.py b/tasks/0046_113_46113496_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0046_113_46113496_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/0046_113_46113496_qa_1/tests/test.sh b/tasks/0046_113_46113496_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0046_113_46113496_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/0046_487_46487066_qa_4/environment/Dockerfile b/tasks/0046_487_46487066_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0046_487_46487066_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0046_487_46487066_qa_4/environment/pull_bucket.py b/tasks/0046_487_46487066_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0046_487_46487066_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/0046_487_46487066_qa_4/tests/grader.py b/tasks/0046_487_46487066_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0046_487_46487066_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/0046_487_46487066_qa_4/tests/test.sh b/tasks/0046_487_46487066_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0046_487_46487066_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/0046_651_46651682_qa_4/environment/Dockerfile b/tasks/0046_651_46651682_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0046_651_46651682_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0046_651_46651682_qa_4/environment/pull_bucket.py b/tasks/0046_651_46651682_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0046_651_46651682_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/0046_651_46651682_qa_4/tests/grader.py b/tasks/0046_651_46651682_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0046_651_46651682_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/0046_651_46651682_qa_4/tests/test.sh b/tasks/0046_651_46651682_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0046_651_46651682_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_308_47308029_qa_1/environment/Dockerfile b/tasks/0047_308_47308029_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0047_308_47308029_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0047_308_47308029_qa_1/environment/pull_bucket.py b/tasks/0047_308_47308029_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0047_308_47308029_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_308_47308029_qa_1/tests/grader.py b/tasks/0047_308_47308029_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0047_308_47308029_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_308_47308029_qa_1/tests/test.sh b/tasks/0047_308_47308029_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0047_308_47308029_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_591_47591946_qa_3/environment/Dockerfile b/tasks/0047_591_47591946_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0047_591_47591946_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0047_591_47591946_qa_3/environment/pull_bucket.py b/tasks/0047_591_47591946_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0047_591_47591946_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/0047_591_47591946_qa_3/tests/grader.py b/tasks/0047_591_47591946_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0047_591_47591946_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/0047_591_47591946_qa_3/tests/test.sh b/tasks/0047_591_47591946_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0047_591_47591946_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/0047_751_47751075_qa_2/environment/Dockerfile b/tasks/0047_751_47751075_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0047_751_47751075_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0047_751_47751075_qa_2/environment/pull_bucket.py b/tasks/0047_751_47751075_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0047_751_47751075_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/0047_751_47751075_qa_2/tests/grader.py b/tasks/0047_751_47751075_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0047_751_47751075_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/0047_751_47751075_qa_2/tests/test.sh b/tasks/0047_751_47751075_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0047_751_47751075_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/0048_436_48436455_qa_2/environment/Dockerfile b/tasks/0048_436_48436455_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0048_436_48436455_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0048_436_48436455_qa_2/environment/pull_bucket.py b/tasks/0048_436_48436455_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0048_436_48436455_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/0048_436_48436455_qa_2/tests/grader.py b/tasks/0048_436_48436455_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0048_436_48436455_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/0048_436_48436455_qa_2/tests/test.sh b/tasks/0048_436_48436455_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0048_436_48436455_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/0049_683_49683426_qa_3/environment/Dockerfile b/tasks/0049_683_49683426_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0049_683_49683426_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0049_683_49683426_qa_3/environment/pull_bucket.py b/tasks/0049_683_49683426_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0049_683_49683426_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/0049_683_49683426_qa_3/tests/grader.py b/tasks/0049_683_49683426_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0049_683_49683426_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/0049_683_49683426_qa_3/tests/test.sh b/tasks/0049_683_49683426_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0049_683_49683426_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/0049_738_49738137_qa_4/environment/Dockerfile b/tasks/0049_738_49738137_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0049_738_49738137_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0049_738_49738137_qa_4/environment/pull_bucket.py b/tasks/0049_738_49738137_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0049_738_49738137_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/0049_738_49738137_qa_4/tests/grader.py b/tasks/0049_738_49738137_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0049_738_49738137_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/0049_738_49738137_qa_4/tests/test.sh b/tasks/0049_738_49738137_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0049_738_49738137_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/0051_529_51529879_qa_4/environment/Dockerfile b/tasks/0051_529_51529879_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0051_529_51529879_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0051_529_51529879_qa_4/environment/pull_bucket.py b/tasks/0051_529_51529879_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0051_529_51529879_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/0051_529_51529879_qa_4/tests/grader.py b/tasks/0051_529_51529879_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0051_529_51529879_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/0051_529_51529879_qa_4/tests/test.sh b/tasks/0051_529_51529879_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0051_529_51529879_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/0051_975_51975834_qa_4/environment/Dockerfile b/tasks/0051_975_51975834_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0051_975_51975834_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0051_975_51975834_qa_4/environment/pull_bucket.py b/tasks/0051_975_51975834_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0051_975_51975834_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/0051_975_51975834_qa_4/tests/grader.py b/tasks/0051_975_51975834_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0051_975_51975834_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/0051_975_51975834_qa_4/tests/test.sh b/tasks/0051_975_51975834_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0051_975_51975834_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/0052_026_52026780_qa_3/environment/Dockerfile b/tasks/0052_026_52026780_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0052_026_52026780_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0052_026_52026780_qa_3/environment/pull_bucket.py b/tasks/0052_026_52026780_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0052_026_52026780_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/0052_026_52026780_qa_3/tests/grader.py b/tasks/0052_026_52026780_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0052_026_52026780_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/0052_026_52026780_qa_3/tests/test.sh b/tasks/0052_026_52026780_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0052_026_52026780_qa_3/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0052_331_52331828_qa_4/environment/Dockerfile b/tasks/0052_331_52331828_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0052_331_52331828_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0052_331_52331828_qa_4/environment/pull_bucket.py b/tasks/0052_331_52331828_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0052_331_52331828_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/0052_331_52331828_qa_4/tests/grader.py b/tasks/0052_331_52331828_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0052_331_52331828_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/0052_331_52331828_qa_4/tests/test.sh b/tasks/0052_331_52331828_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0052_331_52331828_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/0052_712_52712705_qa_3/environment/Dockerfile b/tasks/0052_712_52712705_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0052_712_52712705_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0052_712_52712705_qa_3/environment/pull_bucket.py b/tasks/0052_712_52712705_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0052_712_52712705_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/0052_712_52712705_qa_3/tests/grader.py b/tasks/0052_712_52712705_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0052_712_52712705_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/0052_712_52712705_qa_3/tests/test.sh b/tasks/0052_712_52712705_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0052_712_52712705_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/0053_352_53352624_qa_1/environment/Dockerfile b/tasks/0053_352_53352624_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0053_352_53352624_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0053_352_53352624_qa_1/environment/pull_bucket.py b/tasks/0053_352_53352624_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0053_352_53352624_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/0053_352_53352624_qa_1/tests/grader.py b/tasks/0053_352_53352624_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0053_352_53352624_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/0053_352_53352624_qa_1/tests/test.sh b/tasks/0053_352_53352624_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0053_352_53352624_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/0054_240_54240595_qa_2/environment/Dockerfile b/tasks/0054_240_54240595_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0054_240_54240595_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0054_240_54240595_qa_2/environment/pull_bucket.py b/tasks/0054_240_54240595_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0054_240_54240595_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/0054_240_54240595_qa_2/tests/grader.py b/tasks/0054_240_54240595_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0054_240_54240595_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/0054_240_54240595_qa_2/tests/test.sh b/tasks/0054_240_54240595_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0054_240_54240595_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/0054_266_54266894_qa_3/environment/Dockerfile b/tasks/0054_266_54266894_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0054_266_54266894_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0054_266_54266894_qa_3/environment/pull_bucket.py b/tasks/0054_266_54266894_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0054_266_54266894_qa_3/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0054_266_54266894_qa_3/tests/grader.py b/tasks/0054_266_54266894_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0054_266_54266894_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/0054_266_54266894_qa_3/tests/test.sh b/tasks/0054_266_54266894_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0054_266_54266894_qa_3/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0054_555_54555681_qa_4/environment/Dockerfile b/tasks/0054_555_54555681_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0054_555_54555681_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0054_555_54555681_qa_4/environment/pull_bucket.py b/tasks/0054_555_54555681_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0054_555_54555681_qa_4/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0054_555_54555681_qa_4/tests/grader.py b/tasks/0054_555_54555681_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0054_555_54555681_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/0054_555_54555681_qa_4/tests/test.sh b/tasks/0054_555_54555681_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0054_555_54555681_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/0054_748_54748769_qa_2/environment/Dockerfile b/tasks/0054_748_54748769_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0054_748_54748769_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0054_748_54748769_qa_2/environment/pull_bucket.py b/tasks/0054_748_54748769_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0054_748_54748769_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/0054_748_54748769_qa_2/tests/grader.py b/tasks/0054_748_54748769_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0054_748_54748769_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/0054_748_54748769_qa_2/tests/test.sh b/tasks/0054_748_54748769_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0054_748_54748769_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/0055_824_55824440_qa_5/environment/Dockerfile b/tasks/0055_824_55824440_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0055_824_55824440_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0055_824_55824440_qa_5/environment/pull_bucket.py b/tasks/0055_824_55824440_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0055_824_55824440_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/0055_824_55824440_qa_5/tests/grader.py b/tasks/0055_824_55824440_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0055_824_55824440_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/0055_824_55824440_qa_5/tests/test.sh b/tasks/0055_824_55824440_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0055_824_55824440_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/0055_968_55968459_qa_4/environment/Dockerfile b/tasks/0055_968_55968459_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0055_968_55968459_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0055_968_55968459_qa_4/environment/pull_bucket.py b/tasks/0055_968_55968459_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0055_968_55968459_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/0055_968_55968459_qa_4/tests/grader.py b/tasks/0055_968_55968459_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0055_968_55968459_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/0055_968_55968459_qa_4/tests/test.sh b/tasks/0055_968_55968459_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0055_968_55968459_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/0056_498_56498187_qa_3/environment/Dockerfile b/tasks/0056_498_56498187_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0056_498_56498187_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0056_498_56498187_qa_3/environment/pull_bucket.py b/tasks/0056_498_56498187_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0056_498_56498187_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/0056_498_56498187_qa_3/tests/grader.py b/tasks/0056_498_56498187_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0056_498_56498187_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/0056_498_56498187_qa_3/tests/test.sh b/tasks/0056_498_56498187_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0056_498_56498187_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/0056_687_56687302_qa_2/environment/Dockerfile b/tasks/0056_687_56687302_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0056_687_56687302_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0056_687_56687302_qa_2/environment/pull_bucket.py b/tasks/0056_687_56687302_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0056_687_56687302_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/0056_687_56687302_qa_2/tests/grader.py b/tasks/0056_687_56687302_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0056_687_56687302_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/0056_687_56687302_qa_2/tests/test.sh b/tasks/0056_687_56687302_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0056_687_56687302_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/0056_907_56907084_qa_3/environment/Dockerfile b/tasks/0056_907_56907084_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0056_907_56907084_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0056_907_56907084_qa_3/environment/pull_bucket.py b/tasks/0056_907_56907084_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0056_907_56907084_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/0056_907_56907084_qa_3/tests/grader.py b/tasks/0056_907_56907084_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0056_907_56907084_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/0056_907_56907084_qa_3/tests/test.sh b/tasks/0056_907_56907084_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0056_907_56907084_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/0058_674_58674481_qa_2/environment/Dockerfile b/tasks/0058_674_58674481_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0058_674_58674481_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0058_674_58674481_qa_2/environment/pull_bucket.py b/tasks/0058_674_58674481_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0058_674_58674481_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/0058_674_58674481_qa_2/tests/grader.py b/tasks/0058_674_58674481_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0058_674_58674481_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/0058_674_58674481_qa_2/tests/test.sh b/tasks/0058_674_58674481_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0058_674_58674481_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/0061_736_61736140_qa_4/environment/Dockerfile b/tasks/0061_736_61736140_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0061_736_61736140_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0061_736_61736140_qa_4/environment/pull_bucket.py b/tasks/0061_736_61736140_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0061_736_61736140_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/0061_736_61736140_qa_4/tests/grader.py b/tasks/0061_736_61736140_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0061_736_61736140_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/0061_736_61736140_qa_4/tests/test.sh b/tasks/0061_736_61736140_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0061_736_61736140_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/0062_401_62401866_qa_3/environment/Dockerfile b/tasks/0062_401_62401866_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0062_401_62401866_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0062_401_62401866_qa_3/environment/pull_bucket.py b/tasks/0062_401_62401866_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0062_401_62401866_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/0062_401_62401866_qa_3/tests/grader.py b/tasks/0062_401_62401866_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0062_401_62401866_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/0062_401_62401866_qa_3/tests/test.sh b/tasks/0062_401_62401866_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0062_401_62401866_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/0062_450_62450924_qa_2/environment/Dockerfile b/tasks/0062_450_62450924_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0062_450_62450924_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0062_450_62450924_qa_2/environment/pull_bucket.py b/tasks/0062_450_62450924_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0062_450_62450924_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/0062_450_62450924_qa_2/tests/grader.py b/tasks/0062_450_62450924_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0062_450_62450924_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/0062_450_62450924_qa_2/tests/test.sh b/tasks/0062_450_62450924_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0062_450_62450924_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/0062_653_62653158_qa_5/environment/Dockerfile b/tasks/0062_653_62653158_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0062_653_62653158_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0062_653_62653158_qa_5/environment/pull_bucket.py b/tasks/0062_653_62653158_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0062_653_62653158_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_653_62653158_qa_5/tests/grader.py b/tasks/0062_653_62653158_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0062_653_62653158_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_653_62653158_qa_5/tests/test.sh b/tasks/0062_653_62653158_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0062_653_62653158_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/0063_056_63056064_qa_2/environment/Dockerfile b/tasks/0063_056_63056064_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0063_056_63056064_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0063_056_63056064_qa_2/environment/pull_bucket.py b/tasks/0063_056_63056064_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0063_056_63056064_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/0063_056_63056064_qa_2/tests/grader.py b/tasks/0063_056_63056064_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0063_056_63056064_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/0063_056_63056064_qa_2/tests/test.sh b/tasks/0063_056_63056064_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0063_056_63056064_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/0063_708_63708411_qa_1/environment/Dockerfile b/tasks/0063_708_63708411_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0063_708_63708411_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0063_708_63708411_qa_1/environment/pull_bucket.py b/tasks/0063_708_63708411_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0063_708_63708411_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/0063_708_63708411_qa_1/tests/grader.py b/tasks/0063_708_63708411_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0063_708_63708411_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/0063_708_63708411_qa_1/tests/test.sh b/tasks/0063_708_63708411_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0063_708_63708411_qa_1/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0064_330_64330026_qa_1/environment/Dockerfile b/tasks/0064_330_64330026_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0064_330_64330026_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0064_330_64330026_qa_1/environment/pull_bucket.py b/tasks/0064_330_64330026_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0064_330_64330026_qa_1/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0064_330_64330026_qa_1/tests/grader.py b/tasks/0064_330_64330026_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0064_330_64330026_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/0064_330_64330026_qa_1/tests/test.sh b/tasks/0064_330_64330026_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0064_330_64330026_qa_1/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0064_828_64828278_qa_5/environment/Dockerfile b/tasks/0064_828_64828278_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0064_828_64828278_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0064_828_64828278_qa_5/environment/pull_bucket.py b/tasks/0064_828_64828278_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0064_828_64828278_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/0064_828_64828278_qa_5/tests/grader.py b/tasks/0064_828_64828278_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0064_828_64828278_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/0064_828_64828278_qa_5/tests/test.sh b/tasks/0064_828_64828278_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0064_828_64828278_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_983_64983007_qa_2/environment/Dockerfile b/tasks/0064_983_64983007_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0064_983_64983007_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0064_983_64983007_qa_2/environment/pull_bucket.py b/tasks/0064_983_64983007_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0064_983_64983007_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/0064_983_64983007_qa_2/tests/grader.py b/tasks/0064_983_64983007_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0064_983_64983007_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/0064_983_64983007_qa_2/tests/test.sh b/tasks/0064_983_64983007_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0064_983_64983007_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/0065_495_65495142_qa_3/environment/Dockerfile b/tasks/0065_495_65495142_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0065_495_65495142_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0065_495_65495142_qa_3/environment/pull_bucket.py b/tasks/0065_495_65495142_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0065_495_65495142_qa_3/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0065_495_65495142_qa_3/tests/grader.py b/tasks/0065_495_65495142_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0065_495_65495142_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/0065_495_65495142_qa_3/tests/test.sh b/tasks/0065_495_65495142_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0065_495_65495142_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_563_65563185_qa_4/environment/Dockerfile b/tasks/0065_563_65563185_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0065_563_65563185_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0065_563_65563185_qa_4/environment/pull_bucket.py b/tasks/0065_563_65563185_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0065_563_65563185_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/0065_563_65563185_qa_4/tests/grader.py b/tasks/0065_563_65563185_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0065_563_65563185_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/0065_563_65563185_qa_4/tests/test.sh b/tasks/0065_563_65563185_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0065_563_65563185_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/0065_756_65756425_qa_1/environment/Dockerfile b/tasks/0065_756_65756425_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0065_756_65756425_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0065_756_65756425_qa_1/environment/pull_bucket.py b/tasks/0065_756_65756425_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0065_756_65756425_qa_1/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0065_756_65756425_qa_1/tests/grader.py b/tasks/0065_756_65756425_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0065_756_65756425_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/0065_756_65756425_qa_1/tests/test.sh b/tasks/0065_756_65756425_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0065_756_65756425_qa_1/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0065_850_65850570_qa_3/environment/Dockerfile b/tasks/0065_850_65850570_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0065_850_65850570_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0065_850_65850570_qa_3/environment/pull_bucket.py b/tasks/0065_850_65850570_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0065_850_65850570_qa_3/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0065_850_65850570_qa_3/tests/grader.py b/tasks/0065_850_65850570_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0065_850_65850570_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/0065_850_65850570_qa_3/tests/test.sh b/tasks/0065_850_65850570_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0065_850_65850570_qa_3/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0065_929_65929308_qa_1/environment/Dockerfile b/tasks/0065_929_65929308_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0065_929_65929308_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0065_929_65929308_qa_1/environment/pull_bucket.py b/tasks/0065_929_65929308_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0065_929_65929308_qa_1/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0065_929_65929308_qa_1/tests/grader.py b/tasks/0065_929_65929308_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0065_929_65929308_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/0065_929_65929308_qa_1/tests/test.sh b/tasks/0065_929_65929308_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0065_929_65929308_qa_1/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0066_186_66186009_qa_3/environment/Dockerfile b/tasks/0066_186_66186009_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0066_186_66186009_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0066_186_66186009_qa_3/environment/pull_bucket.py b/tasks/0066_186_66186009_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0066_186_66186009_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/0066_186_66186009_qa_3/tests/grader.py b/tasks/0066_186_66186009_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0066_186_66186009_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/0066_186_66186009_qa_3/tests/test.sh b/tasks/0066_186_66186009_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0066_186_66186009_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/0068_960_68960212_qa_4/environment/Dockerfile b/tasks/0068_960_68960212_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0068_960_68960212_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0068_960_68960212_qa_4/environment/pull_bucket.py b/tasks/0068_960_68960212_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0068_960_68960212_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/0068_960_68960212_qa_4/tests/grader.py b/tasks/0068_960_68960212_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0068_960_68960212_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/0068_960_68960212_qa_4/tests/test.sh b/tasks/0068_960_68960212_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0068_960_68960212_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/0069_294_69294198_qa_5/environment/Dockerfile b/tasks/0069_294_69294198_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0069_294_69294198_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0069_294_69294198_qa_5/environment/pull_bucket.py b/tasks/0069_294_69294198_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0069_294_69294198_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/0069_294_69294198_qa_5/tests/grader.py b/tasks/0069_294_69294198_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0069_294_69294198_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/0069_294_69294198_qa_5/tests/test.sh b/tasks/0069_294_69294198_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0069_294_69294198_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/0069_401_69401499_qa_5/environment/Dockerfile b/tasks/0069_401_69401499_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0069_401_69401499_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0069_401_69401499_qa_5/environment/pull_bucket.py b/tasks/0069_401_69401499_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0069_401_69401499_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/0069_401_69401499_qa_5/tests/grader.py b/tasks/0069_401_69401499_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0069_401_69401499_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/0069_401_69401499_qa_5/tests/test.sh b/tasks/0069_401_69401499_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0069_401_69401499_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/0069_643_69643958_qa_2/environment/Dockerfile b/tasks/0069_643_69643958_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0069_643_69643958_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0069_643_69643958_qa_2/environment/pull_bucket.py b/tasks/0069_643_69643958_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0069_643_69643958_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/0069_643_69643958_qa_2/tests/grader.py b/tasks/0069_643_69643958_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0069_643_69643958_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/0069_643_69643958_qa_2/tests/test.sh b/tasks/0069_643_69643958_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0069_643_69643958_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/0071_845_71845804_qa_1/environment/Dockerfile b/tasks/0071_845_71845804_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0071_845_71845804_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0071_845_71845804_qa_1/environment/pull_bucket.py b/tasks/0071_845_71845804_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0071_845_71845804_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/0071_845_71845804_qa_1/tests/grader.py b/tasks/0071_845_71845804_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0071_845_71845804_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/0071_845_71845804_qa_1/tests/test.sh b/tasks/0071_845_71845804_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0071_845_71845804_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/0072_071_72071082_qa_5/environment/Dockerfile b/tasks/0072_071_72071082_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0072_071_72071082_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0072_071_72071082_qa_5/environment/pull_bucket.py b/tasks/0072_071_72071082_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0072_071_72071082_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/0072_071_72071082_qa_5/tests/grader.py b/tasks/0072_071_72071082_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0072_071_72071082_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/0072_071_72071082_qa_5/tests/test.sh b/tasks/0072_071_72071082_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0072_071_72071082_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/0073_439_73439547_qa_3/environment/Dockerfile b/tasks/0073_439_73439547_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0073_439_73439547_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0073_439_73439547_qa_3/environment/pull_bucket.py b/tasks/0073_439_73439547_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0073_439_73439547_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/0073_439_73439547_qa_3/tests/grader.py b/tasks/0073_439_73439547_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0073_439_73439547_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/0073_439_73439547_qa_3/tests/test.sh b/tasks/0073_439_73439547_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0073_439_73439547_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/0074_501_74501235_qa_2/environment/Dockerfile b/tasks/0074_501_74501235_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0074_501_74501235_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0074_501_74501235_qa_2/environment/pull_bucket.py b/tasks/0074_501_74501235_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0074_501_74501235_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_501_74501235_qa_2/tests/grader.py b/tasks/0074_501_74501235_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0074_501_74501235_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_501_74501235_qa_2/tests/test.sh b/tasks/0074_501_74501235_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0074_501_74501235_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/0075_148_75148017_qa_1/environment/Dockerfile b/tasks/0075_148_75148017_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0075_148_75148017_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0075_148_75148017_qa_1/environment/pull_bucket.py b/tasks/0075_148_75148017_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0075_148_75148017_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/0075_148_75148017_qa_1/tests/grader.py b/tasks/0075_148_75148017_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0075_148_75148017_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/0075_148_75148017_qa_1/tests/test.sh b/tasks/0075_148_75148017_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0075_148_75148017_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/0075_890_75890673_qa_3/environment/Dockerfile b/tasks/0075_890_75890673_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0075_890_75890673_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0075_890_75890673_qa_3/environment/pull_bucket.py b/tasks/0075_890_75890673_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0075_890_75890673_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/0075_890_75890673_qa_3/tests/grader.py b/tasks/0075_890_75890673_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0075_890_75890673_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/0075_890_75890673_qa_3/tests/test.sh b/tasks/0075_890_75890673_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0075_890_75890673_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/0075_890_75890673_qa_4/environment/Dockerfile b/tasks/0075_890_75890673_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0075_890_75890673_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0075_890_75890673_qa_4/environment/pull_bucket.py b/tasks/0075_890_75890673_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0075_890_75890673_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/0075_890_75890673_qa_4/tests/grader.py b/tasks/0075_890_75890673_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0075_890_75890673_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/0075_890_75890673_qa_4/tests/test.sh b/tasks/0075_890_75890673_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0075_890_75890673_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/0077_529_77529364_qa_3/environment/Dockerfile b/tasks/0077_529_77529364_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0077_529_77529364_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0077_529_77529364_qa_3/environment/pull_bucket.py b/tasks/0077_529_77529364_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0077_529_77529364_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_529_77529364_qa_3/tests/grader.py b/tasks/0077_529_77529364_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0077_529_77529364_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_529_77529364_qa_3/tests/test.sh b/tasks/0077_529_77529364_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0077_529_77529364_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/0077_572_77572617_qa_3/environment/Dockerfile b/tasks/0077_572_77572617_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0077_572_77572617_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0077_572_77572617_qa_3/environment/pull_bucket.py b/tasks/0077_572_77572617_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0077_572_77572617_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_572_77572617_qa_3/tests/grader.py b/tasks/0077_572_77572617_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0077_572_77572617_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_572_77572617_qa_3/tests/test.sh b/tasks/0077_572_77572617_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0077_572_77572617_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/0077_578_77578267_qa_2/environment/Dockerfile b/tasks/0077_578_77578267_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0077_578_77578267_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0077_578_77578267_qa_2/environment/pull_bucket.py b/tasks/0077_578_77578267_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0077_578_77578267_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/0077_578_77578267_qa_2/tests/grader.py b/tasks/0077_578_77578267_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0077_578_77578267_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/0077_578_77578267_qa_2/tests/test.sh b/tasks/0077_578_77578267_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0077_578_77578267_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/0079_597_79597687_qa_2/environment/Dockerfile b/tasks/0079_597_79597687_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0079_597_79597687_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0079_597_79597687_qa_2/environment/pull_bucket.py b/tasks/0079_597_79597687_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0079_597_79597687_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/0079_597_79597687_qa_2/tests/grader.py b/tasks/0079_597_79597687_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0079_597_79597687_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/0079_597_79597687_qa_2/tests/test.sh b/tasks/0079_597_79597687_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0079_597_79597687_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/0079_852_79852470_qa_4/environment/Dockerfile b/tasks/0079_852_79852470_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0079_852_79852470_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0079_852_79852470_qa_4/environment/pull_bucket.py b/tasks/0079_852_79852470_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0079_852_79852470_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/0079_852_79852470_qa_4/tests/grader.py b/tasks/0079_852_79852470_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0079_852_79852470_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/0079_852_79852470_qa_4/tests/test.sh b/tasks/0079_852_79852470_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0079_852_79852470_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/0080_011_80011409_qa_2/environment/Dockerfile b/tasks/0080_011_80011409_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0080_011_80011409_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0080_011_80011409_qa_2/environment/pull_bucket.py b/tasks/0080_011_80011409_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0080_011_80011409_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/0080_011_80011409_qa_2/tests/grader.py b/tasks/0080_011_80011409_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0080_011_80011409_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/0080_011_80011409_qa_2/tests/test.sh b/tasks/0080_011_80011409_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0080_011_80011409_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/0080_011_80011409_qa_3/environment/Dockerfile b/tasks/0080_011_80011409_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0080_011_80011409_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0080_011_80011409_qa_3/environment/pull_bucket.py b/tasks/0080_011_80011409_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0080_011_80011409_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/0080_011_80011409_qa_3/tests/grader.py b/tasks/0080_011_80011409_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0080_011_80011409_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/0080_011_80011409_qa_3/tests/test.sh b/tasks/0080_011_80011409_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0080_011_80011409_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_011_80011409_qa_4/environment/Dockerfile b/tasks/0080_011_80011409_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0080_011_80011409_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0080_011_80011409_qa_4/environment/pull_bucket.py b/tasks/0080_011_80011409_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0080_011_80011409_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/0080_011_80011409_qa_4/tests/grader.py b/tasks/0080_011_80011409_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0080_011_80011409_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/0080_011_80011409_qa_4/tests/test.sh b/tasks/0080_011_80011409_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0080_011_80011409_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/0081_468_81468620_qa_4/environment/Dockerfile b/tasks/0081_468_81468620_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0081_468_81468620_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0081_468_81468620_qa_4/environment/pull_bucket.py b/tasks/0081_468_81468620_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0081_468_81468620_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/0081_468_81468620_qa_4/tests/grader.py b/tasks/0081_468_81468620_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0081_468_81468620_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/0081_468_81468620_qa_4/tests/test.sh b/tasks/0081_468_81468620_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0081_468_81468620_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/0083_238_83238182_qa_2/environment/Dockerfile b/tasks/0083_238_83238182_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0083_238_83238182_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0083_238_83238182_qa_2/environment/pull_bucket.py b/tasks/0083_238_83238182_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0083_238_83238182_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/0083_238_83238182_qa_2/tests/grader.py b/tasks/0083_238_83238182_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0083_238_83238182_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/0083_238_83238182_qa_2/tests/test.sh b/tasks/0083_238_83238182_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0083_238_83238182_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/0083_317_83317900_qa_1/environment/Dockerfile b/tasks/0083_317_83317900_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0083_317_83317900_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0083_317_83317900_qa_1/environment/pull_bucket.py b/tasks/0083_317_83317900_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0083_317_83317900_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/0083_317_83317900_qa_1/tests/grader.py b/tasks/0083_317_83317900_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0083_317_83317900_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/0083_317_83317900_qa_1/tests/test.sh b/tasks/0083_317_83317900_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0083_317_83317900_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/0085_359_85359585_qa_5/environment/Dockerfile b/tasks/0085_359_85359585_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0085_359_85359585_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0085_359_85359585_qa_5/environment/pull_bucket.py b/tasks/0085_359_85359585_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0085_359_85359585_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/0085_359_85359585_qa_5/tests/grader.py b/tasks/0085_359_85359585_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0085_359_85359585_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/0085_359_85359585_qa_5/tests/test.sh b/tasks/0085_359_85359585_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0085_359_85359585_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/0085_706_85706685_qa_2/environment/Dockerfile b/tasks/0085_706_85706685_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0085_706_85706685_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0085_706_85706685_qa_2/environment/pull_bucket.py b/tasks/0085_706_85706685_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0085_706_85706685_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/0085_706_85706685_qa_2/tests/grader.py b/tasks/0085_706_85706685_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0085_706_85706685_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/0085_706_85706685_qa_2/tests/test.sh b/tasks/0085_706_85706685_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0085_706_85706685_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/0086_499_86499791_qa_5/environment/Dockerfile b/tasks/0086_499_86499791_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0086_499_86499791_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0086_499_86499791_qa_5/environment/pull_bucket.py b/tasks/0086_499_86499791_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0086_499_86499791_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/0086_499_86499791_qa_5/tests/grader.py b/tasks/0086_499_86499791_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0086_499_86499791_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/0086_499_86499791_qa_5/tests/test.sh b/tasks/0086_499_86499791_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0086_499_86499791_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/0087_290_87290637_qa_1/environment/Dockerfile b/tasks/0087_290_87290637_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0087_290_87290637_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0087_290_87290637_qa_1/environment/pull_bucket.py b/tasks/0087_290_87290637_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0087_290_87290637_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/0087_290_87290637_qa_1/tests/grader.py b/tasks/0087_290_87290637_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0087_290_87290637_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/0087_290_87290637_qa_1/tests/test.sh b/tasks/0087_290_87290637_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0087_290_87290637_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/0087_349_87349607_qa_1/environment/Dockerfile b/tasks/0087_349_87349607_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0087_349_87349607_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0087_349_87349607_qa_1/environment/pull_bucket.py b/tasks/0087_349_87349607_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0087_349_87349607_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/0087_349_87349607_qa_1/tests/grader.py b/tasks/0087_349_87349607_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0087_349_87349607_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/0087_349_87349607_qa_1/tests/test.sh b/tasks/0087_349_87349607_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0087_349_87349607_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/0088_108_88108629_qa_1/environment/Dockerfile b/tasks/0088_108_88108629_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0088_108_88108629_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0088_108_88108629_qa_1/environment/pull_bucket.py b/tasks/0088_108_88108629_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0088_108_88108629_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/0088_108_88108629_qa_1/tests/grader.py b/tasks/0088_108_88108629_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0088_108_88108629_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/0088_108_88108629_qa_1/tests/test.sh b/tasks/0088_108_88108629_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0088_108_88108629_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/0088_214_88214420_qa_3/environment/Dockerfile b/tasks/0088_214_88214420_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0088_214_88214420_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0088_214_88214420_qa_3/environment/pull_bucket.py b/tasks/0088_214_88214420_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0088_214_88214420_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/0088_214_88214420_qa_3/tests/grader.py b/tasks/0088_214_88214420_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0088_214_88214420_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/0088_214_88214420_qa_3/tests/test.sh b/tasks/0088_214_88214420_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0088_214_88214420_qa_3/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0088_417_88417673_qa_1/environment/Dockerfile b/tasks/0088_417_88417673_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0088_417_88417673_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0088_417_88417673_qa_1/environment/pull_bucket.py b/tasks/0088_417_88417673_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0088_417_88417673_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/0088_417_88417673_qa_1/tests/grader.py b/tasks/0088_417_88417673_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0088_417_88417673_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/0088_417_88417673_qa_1/tests/test.sh b/tasks/0088_417_88417673_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0088_417_88417673_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/0088_996_88996860_qa_1/environment/Dockerfile b/tasks/0088_996_88996860_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0088_996_88996860_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0088_996_88996860_qa_1/environment/pull_bucket.py b/tasks/0088_996_88996860_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0088_996_88996860_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/0088_996_88996860_qa_1/tests/grader.py b/tasks/0088_996_88996860_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0088_996_88996860_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/0088_996_88996860_qa_1/tests/test.sh b/tasks/0088_996_88996860_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0088_996_88996860_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/0091_122_91122496_qa_5/environment/Dockerfile b/tasks/0091_122_91122496_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0091_122_91122496_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0091_122_91122496_qa_5/environment/pull_bucket.py b/tasks/0091_122_91122496_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0091_122_91122496_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/0091_122_91122496_qa_5/tests/grader.py b/tasks/0091_122_91122496_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0091_122_91122496_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/0091_122_91122496_qa_5/tests/test.sh b/tasks/0091_122_91122496_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0091_122_91122496_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/0091_861_91861304_qa_1/environment/Dockerfile b/tasks/0091_861_91861304_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0091_861_91861304_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0091_861_91861304_qa_1/environment/pull_bucket.py b/tasks/0091_861_91861304_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0091_861_91861304_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/0091_861_91861304_qa_1/tests/grader.py b/tasks/0091_861_91861304_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0091_861_91861304_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/0091_861_91861304_qa_1/tests/test.sh b/tasks/0091_861_91861304_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0091_861_91861304_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/0093_170_93170596_qa_1/environment/Dockerfile b/tasks/0093_170_93170596_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0093_170_93170596_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0093_170_93170596_qa_1/environment/pull_bucket.py b/tasks/0093_170_93170596_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0093_170_93170596_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/0093_170_93170596_qa_1/tests/grader.py b/tasks/0093_170_93170596_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0093_170_93170596_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/0093_170_93170596_qa_1/tests/test.sh b/tasks/0093_170_93170596_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0093_170_93170596_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/0093_813_93813737_qa_1/environment/Dockerfile b/tasks/0093_813_93813737_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0093_813_93813737_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0093_813_93813737_qa_1/environment/pull_bucket.py b/tasks/0093_813_93813737_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0093_813_93813737_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/0093_813_93813737_qa_1/tests/grader.py b/tasks/0093_813_93813737_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0093_813_93813737_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/0093_813_93813737_qa_1/tests/test.sh b/tasks/0093_813_93813737_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0093_813_93813737_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/0095_344_95344142_qa_3/environment/Dockerfile b/tasks/0095_344_95344142_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0095_344_95344142_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0095_344_95344142_qa_3/environment/pull_bucket.py b/tasks/0095_344_95344142_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0095_344_95344142_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/0095_344_95344142_qa_3/tests/grader.py b/tasks/0095_344_95344142_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0095_344_95344142_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/0095_344_95344142_qa_3/tests/test.sh b/tasks/0095_344_95344142_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0095_344_95344142_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/0095_344_95344142_qa_4/environment/Dockerfile b/tasks/0095_344_95344142_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0095_344_95344142_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0095_344_95344142_qa_4/environment/pull_bucket.py b/tasks/0095_344_95344142_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0095_344_95344142_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/0095_344_95344142_qa_4/tests/grader.py b/tasks/0095_344_95344142_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0095_344_95344142_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/0095_344_95344142_qa_4/tests/test.sh b/tasks/0095_344_95344142_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0095_344_95344142_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/0095_843_95843375_qa_3/environment/Dockerfile b/tasks/0095_843_95843375_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0095_843_95843375_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0095_843_95843375_qa_3/environment/pull_bucket.py b/tasks/0095_843_95843375_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0095_843_95843375_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/0095_843_95843375_qa_3/tests/grader.py b/tasks/0095_843_95843375_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0095_843_95843375_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/0095_843_95843375_qa_3/tests/test.sh b/tasks/0095_843_95843375_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0095_843_95843375_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/0096_064_96064872_qa_1/environment/Dockerfile b/tasks/0096_064_96064872_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0096_064_96064872_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0096_064_96064872_qa_1/environment/pull_bucket.py b/tasks/0096_064_96064872_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0096_064_96064872_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/0096_064_96064872_qa_1/tests/grader.py b/tasks/0096_064_96064872_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0096_064_96064872_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/0096_064_96064872_qa_1/tests/test.sh b/tasks/0096_064_96064872_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0096_064_96064872_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/0096_889_96889516_qa_4/environment/Dockerfile b/tasks/0096_889_96889516_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0096_889_96889516_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0096_889_96889516_qa_4/environment/pull_bucket.py b/tasks/0096_889_96889516_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0096_889_96889516_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/0096_889_96889516_qa_4/tests/grader.py b/tasks/0096_889_96889516_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0096_889_96889516_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/0096_889_96889516_qa_4/tests/test.sh b/tasks/0096_889_96889516_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0096_889_96889516_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/0096_889_96889516_qa_5/environment/Dockerfile b/tasks/0096_889_96889516_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0096_889_96889516_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0096_889_96889516_qa_5/environment/pull_bucket.py b/tasks/0096_889_96889516_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0096_889_96889516_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/0096_889_96889516_qa_5/tests/grader.py b/tasks/0096_889_96889516_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0096_889_96889516_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/0096_889_96889516_qa_5/tests/test.sh b/tasks/0096_889_96889516_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0096_889_96889516_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/0097_809_97809761_qa_2/environment/Dockerfile b/tasks/0097_809_97809761_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0097_809_97809761_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0097_809_97809761_qa_2/environment/pull_bucket.py b/tasks/0097_809_97809761_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0097_809_97809761_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/0097_809_97809761_qa_2/tests/grader.py b/tasks/0097_809_97809761_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0097_809_97809761_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/0097_809_97809761_qa_2/tests/test.sh b/tasks/0097_809_97809761_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0097_809_97809761_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/0098_812_98812520_qa_4/environment/Dockerfile b/tasks/0098_812_98812520_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0098_812_98812520_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0098_812_98812520_qa_4/environment/pull_bucket.py b/tasks/0098_812_98812520_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0098_812_98812520_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/0098_812_98812520_qa_4/tests/grader.py b/tasks/0098_812_98812520_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0098_812_98812520_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/0098_812_98812520_qa_4/tests/test.sh b/tasks/0098_812_98812520_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0098_812_98812520_qa_4/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0099_705_99705765_qa_5/environment/Dockerfile b/tasks/0099_705_99705765_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0099_705_99705765_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0099_705_99705765_qa_5/environment/pull_bucket.py b/tasks/0099_705_99705765_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0099_705_99705765_qa_5/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0099_705_99705765_qa_5/tests/grader.py b/tasks/0099_705_99705765_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0099_705_99705765_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/0099_705_99705765_qa_5/tests/test.sh b/tasks/0099_705_99705765_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0099_705_99705765_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/0099_730_99730639_qa_2/environment/Dockerfile b/tasks/0099_730_99730639_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0099_730_99730639_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0099_730_99730639_qa_2/environment/pull_bucket.py b/tasks/0099_730_99730639_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0099_730_99730639_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/0099_730_99730639_qa_2/tests/grader.py b/tasks/0099_730_99730639_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0099_730_99730639_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/0099_730_99730639_qa_2/tests/test.sh b/tasks/0099_730_99730639_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0099_730_99730639_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/0101_142_101142803_qa_4/environment/Dockerfile b/tasks/0101_142_101142803_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0101_142_101142803_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0101_142_101142803_qa_4/environment/pull_bucket.py b/tasks/0101_142_101142803_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0101_142_101142803_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/0101_142_101142803_qa_4/tests/grader.py b/tasks/0101_142_101142803_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0101_142_101142803_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/0101_142_101142803_qa_4/tests/test.sh b/tasks/0101_142_101142803_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0101_142_101142803_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/0101_773_101773827_qa_4/environment/Dockerfile b/tasks/0101_773_101773827_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0101_773_101773827_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0101_773_101773827_qa_4/environment/pull_bucket.py b/tasks/0101_773_101773827_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0101_773_101773827_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/0101_773_101773827_qa_4/tests/grader.py b/tasks/0101_773_101773827_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0101_773_101773827_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/0101_773_101773827_qa_4/tests/test.sh b/tasks/0101_773_101773827_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0101_773_101773827_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/0102_198_102198537_qa_5/environment/Dockerfile b/tasks/0102_198_102198537_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0102_198_102198537_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0102_198_102198537_qa_5/environment/pull_bucket.py b/tasks/0102_198_102198537_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0102_198_102198537_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/0102_198_102198537_qa_5/tests/grader.py b/tasks/0102_198_102198537_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0102_198_102198537_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/0102_198_102198537_qa_5/tests/test.sh b/tasks/0102_198_102198537_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0102_198_102198537_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/0102_213_102213799_qa_1/environment/Dockerfile b/tasks/0102_213_102213799_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0102_213_102213799_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0102_213_102213799_qa_1/environment/pull_bucket.py b/tasks/0102_213_102213799_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0102_213_102213799_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/0102_213_102213799_qa_1/tests/grader.py b/tasks/0102_213_102213799_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0102_213_102213799_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/0102_213_102213799_qa_1/tests/test.sh b/tasks/0102_213_102213799_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0102_213_102213799_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/0102_436_102436012_qa_1/environment/Dockerfile b/tasks/0102_436_102436012_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0102_436_102436012_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0102_436_102436012_qa_1/environment/pull_bucket.py b/tasks/0102_436_102436012_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0102_436_102436012_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/0102_436_102436012_qa_1/tests/grader.py b/tasks/0102_436_102436012_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0102_436_102436012_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/0102_436_102436012_qa_1/tests/test.sh b/tasks/0102_436_102436012_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0102_436_102436012_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/0102_982_102982156_qa_3/environment/Dockerfile b/tasks/0102_982_102982156_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0102_982_102982156_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0102_982_102982156_qa_3/environment/pull_bucket.py b/tasks/0102_982_102982156_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0102_982_102982156_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/0102_982_102982156_qa_3/tests/grader.py b/tasks/0102_982_102982156_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0102_982_102982156_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/0102_982_102982156_qa_3/tests/test.sh b/tasks/0102_982_102982156_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0102_982_102982156_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/0102_982_102982156_qa_4/environment/Dockerfile b/tasks/0102_982_102982156_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0102_982_102982156_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0102_982_102982156_qa_4/environment/pull_bucket.py b/tasks/0102_982_102982156_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0102_982_102982156_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/0102_982_102982156_qa_4/tests/grader.py b/tasks/0102_982_102982156_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0102_982_102982156_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/0102_982_102982156_qa_4/tests/test.sh b/tasks/0102_982_102982156_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0102_982_102982156_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_096_103096538_qa_3/environment/Dockerfile b/tasks/0103_096_103096538_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0103_096_103096538_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0103_096_103096538_qa_3/environment/pull_bucket.py b/tasks/0103_096_103096538_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0103_096_103096538_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/0103_096_103096538_qa_3/tests/grader.py b/tasks/0103_096_103096538_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0103_096_103096538_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/0103_096_103096538_qa_3/tests/test.sh b/tasks/0103_096_103096538_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0103_096_103096538_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/0104_261_104261356_qa_5/environment/Dockerfile b/tasks/0104_261_104261356_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0104_261_104261356_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0104_261_104261356_qa_5/environment/pull_bucket.py b/tasks/0104_261_104261356_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0104_261_104261356_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/0104_261_104261356_qa_5/tests/grader.py b/tasks/0104_261_104261356_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0104_261_104261356_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/0104_261_104261356_qa_5/tests/test.sh b/tasks/0104_261_104261356_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0104_261_104261356_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/0104_868_104868299_qa_1/environment/Dockerfile b/tasks/0104_868_104868299_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0104_868_104868299_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0104_868_104868299_qa_1/environment/pull_bucket.py b/tasks/0104_868_104868299_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0104_868_104868299_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/0104_868_104868299_qa_1/tests/grader.py b/tasks/0104_868_104868299_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0104_868_104868299_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/0104_868_104868299_qa_1/tests/test.sh b/tasks/0104_868_104868299_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0104_868_104868299_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/0105_115_105115907_qa_1/environment/Dockerfile b/tasks/0105_115_105115907_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0105_115_105115907_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0105_115_105115907_qa_1/environment/pull_bucket.py b/tasks/0105_115_105115907_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0105_115_105115907_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/0105_115_105115907_qa_1/tests/grader.py b/tasks/0105_115_105115907_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0105_115_105115907_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/0105_115_105115907_qa_1/tests/test.sh b/tasks/0105_115_105115907_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0105_115_105115907_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/0105_684_105684857_qa_4/environment/Dockerfile b/tasks/0105_684_105684857_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0105_684_105684857_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0105_684_105684857_qa_4/environment/pull_bucket.py b/tasks/0105_684_105684857_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0105_684_105684857_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/0105_684_105684857_qa_4/tests/grader.py b/tasks/0105_684_105684857_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0105_684_105684857_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/0105_684_105684857_qa_4/tests/test.sh b/tasks/0105_684_105684857_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0105_684_105684857_qa_4/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0107_417_107417136_qa_1/environment/Dockerfile b/tasks/0107_417_107417136_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0107_417_107417136_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0107_417_107417136_qa_1/environment/pull_bucket.py b/tasks/0107_417_107417136_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0107_417_107417136_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/0107_417_107417136_qa_1/tests/grader.py b/tasks/0107_417_107417136_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0107_417_107417136_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/0107_417_107417136_qa_1/tests/test.sh b/tasks/0107_417_107417136_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0107_417_107417136_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/0107_762_107762409_qa_5/environment/Dockerfile b/tasks/0107_762_107762409_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0107_762_107762409_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0107_762_107762409_qa_5/environment/pull_bucket.py b/tasks/0107_762_107762409_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0107_762_107762409_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/0107_762_107762409_qa_5/tests/grader.py b/tasks/0107_762_107762409_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0107_762_107762409_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/0107_762_107762409_qa_5/tests/test.sh b/tasks/0107_762_107762409_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0107_762_107762409_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/0108_842_108842160_qa_4/environment/Dockerfile b/tasks/0108_842_108842160_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0108_842_108842160_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0108_842_108842160_qa_4/environment/pull_bucket.py b/tasks/0108_842_108842160_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0108_842_108842160_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/0108_842_108842160_qa_4/tests/grader.py b/tasks/0108_842_108842160_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0108_842_108842160_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/0108_842_108842160_qa_4/tests/test.sh b/tasks/0108_842_108842160_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0108_842_108842160_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/0109_442_109442355_qa_4/environment/Dockerfile b/tasks/0109_442_109442355_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0109_442_109442355_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0109_442_109442355_qa_4/environment/pull_bucket.py b/tasks/0109_442_109442355_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0109_442_109442355_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/0109_442_109442355_qa_4/tests/grader.py b/tasks/0109_442_109442355_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0109_442_109442355_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/0109_442_109442355_qa_4/tests/test.sh b/tasks/0109_442_109442355_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0109_442_109442355_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/0109_878_109878873_qa_3/environment/Dockerfile b/tasks/0109_878_109878873_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0109_878_109878873_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0109_878_109878873_qa_3/environment/pull_bucket.py b/tasks/0109_878_109878873_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0109_878_109878873_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/0109_878_109878873_qa_3/tests/grader.py b/tasks/0109_878_109878873_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0109_878_109878873_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/0109_878_109878873_qa_3/tests/test.sh b/tasks/0109_878_109878873_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0109_878_109878873_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/0112_857_112857611_qa_4/environment/Dockerfile b/tasks/0112_857_112857611_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0112_857_112857611_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0112_857_112857611_qa_4/environment/pull_bucket.py b/tasks/0112_857_112857611_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0112_857_112857611_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/0112_857_112857611_qa_4/tests/grader.py b/tasks/0112_857_112857611_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0112_857_112857611_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/0112_857_112857611_qa_4/tests/test.sh b/tasks/0112_857_112857611_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0112_857_112857611_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/0113_060_113060572_qa_1/environment/Dockerfile b/tasks/0113_060_113060572_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0113_060_113060572_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0113_060_113060572_qa_1/environment/pull_bucket.py b/tasks/0113_060_113060572_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0113_060_113060572_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/0113_060_113060572_qa_1/tests/grader.py b/tasks/0113_060_113060572_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0113_060_113060572_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/0113_060_113060572_qa_1/tests/test.sh b/tasks/0113_060_113060572_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0113_060_113060572_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/0113_222_113222481_qa_3/environment/Dockerfile b/tasks/0113_222_113222481_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0113_222_113222481_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0113_222_113222481_qa_3/environment/pull_bucket.py b/tasks/0113_222_113222481_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0113_222_113222481_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/0113_222_113222481_qa_3/tests/grader.py b/tasks/0113_222_113222481_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0113_222_113222481_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/0113_222_113222481_qa_3/tests/test.sh b/tasks/0113_222_113222481_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0113_222_113222481_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/0114_161_114161356_qa_1/environment/Dockerfile b/tasks/0114_161_114161356_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0114_161_114161356_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0114_161_114161356_qa_1/environment/pull_bucket.py b/tasks/0114_161_114161356_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0114_161_114161356_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/0114_161_114161356_qa_1/tests/grader.py b/tasks/0114_161_114161356_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0114_161_114161356_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/0114_161_114161356_qa_1/tests/test.sh b/tasks/0114_161_114161356_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0114_161_114161356_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/0114_525_114525119_qa_3/environment/Dockerfile b/tasks/0114_525_114525119_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0114_525_114525119_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0114_525_114525119_qa_3/environment/pull_bucket.py b/tasks/0114_525_114525119_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0114_525_114525119_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/0114_525_114525119_qa_3/tests/grader.py b/tasks/0114_525_114525119_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0114_525_114525119_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/0114_525_114525119_qa_3/tests/test.sh b/tasks/0114_525_114525119_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0114_525_114525119_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/0114_908_114908217_qa_4/environment/Dockerfile b/tasks/0114_908_114908217_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0114_908_114908217_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0114_908_114908217_qa_4/environment/pull_bucket.py b/tasks/0114_908_114908217_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0114_908_114908217_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/0114_908_114908217_qa_4/tests/grader.py b/tasks/0114_908_114908217_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0114_908_114908217_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/0114_908_114908217_qa_4/tests/test.sh b/tasks/0114_908_114908217_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0114_908_114908217_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/0115_266_115266605_qa_3/environment/Dockerfile b/tasks/0115_266_115266605_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0115_266_115266605_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0115_266_115266605_qa_3/environment/pull_bucket.py b/tasks/0115_266_115266605_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0115_266_115266605_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/0115_266_115266605_qa_3/tests/grader.py b/tasks/0115_266_115266605_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0115_266_115266605_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/0115_266_115266605_qa_3/tests/test.sh b/tasks/0115_266_115266605_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0115_266_115266605_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/0115_532_115532151_qa_3/environment/Dockerfile b/tasks/0115_532_115532151_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0115_532_115532151_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0115_532_115532151_qa_3/environment/pull_bucket.py b/tasks/0115_532_115532151_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0115_532_115532151_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/0115_532_115532151_qa_3/tests/grader.py b/tasks/0115_532_115532151_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0115_532_115532151_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/0115_532_115532151_qa_3/tests/test.sh b/tasks/0115_532_115532151_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0115_532_115532151_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/0115_972_115972863_qa_1/environment/Dockerfile b/tasks/0115_972_115972863_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0115_972_115972863_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0115_972_115972863_qa_1/environment/pull_bucket.py b/tasks/0115_972_115972863_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0115_972_115972863_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/0115_972_115972863_qa_1/tests/grader.py b/tasks/0115_972_115972863_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0115_972_115972863_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/0115_972_115972863_qa_1/tests/test.sh b/tasks/0115_972_115972863_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0115_972_115972863_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_418_116418769_qa_4/environment/Dockerfile b/tasks/0116_418_116418769_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0116_418_116418769_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0116_418_116418769_qa_4/environment/pull_bucket.py b/tasks/0116_418_116418769_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0116_418_116418769_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/0116_418_116418769_qa_4/tests/grader.py b/tasks/0116_418_116418769_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0116_418_116418769_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/0116_418_116418769_qa_4/tests/test.sh b/tasks/0116_418_116418769_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0116_418_116418769_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/0118_088_118088123_qa_1/environment/Dockerfile b/tasks/0118_088_118088123_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0118_088_118088123_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0118_088_118088123_qa_1/environment/pull_bucket.py b/tasks/0118_088_118088123_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0118_088_118088123_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/0118_088_118088123_qa_1/tests/grader.py b/tasks/0118_088_118088123_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0118_088_118088123_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/0118_088_118088123_qa_1/tests/test.sh b/tasks/0118_088_118088123_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0118_088_118088123_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/0118_265_118265412_qa_5/environment/Dockerfile b/tasks/0118_265_118265412_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0118_265_118265412_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0118_265_118265412_qa_5/environment/pull_bucket.py b/tasks/0118_265_118265412_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0118_265_118265412_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/0118_265_118265412_qa_5/tests/grader.py b/tasks/0118_265_118265412_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0118_265_118265412_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/0118_265_118265412_qa_5/tests/test.sh b/tasks/0118_265_118265412_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0118_265_118265412_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/0119_554_119554814_qa_1/environment/Dockerfile b/tasks/0119_554_119554814_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0119_554_119554814_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0119_554_119554814_qa_1/environment/pull_bucket.py b/tasks/0119_554_119554814_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0119_554_119554814_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/0119_554_119554814_qa_1/tests/grader.py b/tasks/0119_554_119554814_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0119_554_119554814_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/0119_554_119554814_qa_1/tests/test.sh b/tasks/0119_554_119554814_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0119_554_119554814_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/0119_666_119666168_qa_2/environment/Dockerfile b/tasks/0119_666_119666168_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0119_666_119666168_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0119_666_119666168_qa_2/environment/pull_bucket.py b/tasks/0119_666_119666168_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0119_666_119666168_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/0119_666_119666168_qa_2/tests/grader.py b/tasks/0119_666_119666168_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0119_666_119666168_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/0119_666_119666168_qa_2/tests/test.sh b/tasks/0119_666_119666168_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0119_666_119666168_qa_2/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0119_926_119926274_qa_5/environment/Dockerfile b/tasks/0119_926_119926274_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0119_926_119926274_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0119_926_119926274_qa_5/environment/pull_bucket.py b/tasks/0119_926_119926274_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0119_926_119926274_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/0119_926_119926274_qa_5/tests/grader.py b/tasks/0119_926_119926274_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0119_926_119926274_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/0119_926_119926274_qa_5/tests/test.sh b/tasks/0119_926_119926274_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0119_926_119926274_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/0120_525_120525884_qa_4/environment/Dockerfile b/tasks/0120_525_120525884_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0120_525_120525884_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0120_525_120525884_qa_4/environment/pull_bucket.py b/tasks/0120_525_120525884_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0120_525_120525884_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/0120_525_120525884_qa_4/tests/grader.py b/tasks/0120_525_120525884_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0120_525_120525884_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/0120_525_120525884_qa_4/tests/test.sh b/tasks/0120_525_120525884_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0120_525_120525884_qa_4/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0123_217_123217664_qa_1/environment/Dockerfile b/tasks/0123_217_123217664_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0123_217_123217664_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0123_217_123217664_qa_1/environment/pull_bucket.py b/tasks/0123_217_123217664_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0123_217_123217664_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/0123_217_123217664_qa_1/tests/grader.py b/tasks/0123_217_123217664_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0123_217_123217664_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/0123_217_123217664_qa_1/tests/test.sh b/tasks/0123_217_123217664_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0123_217_123217664_qa_1/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0124_739_124739657_qa_1/environment/Dockerfile b/tasks/0124_739_124739657_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0124_739_124739657_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0124_739_124739657_qa_1/environment/pull_bucket.py b/tasks/0124_739_124739657_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0124_739_124739657_qa_1/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0124_739_124739657_qa_1/tests/grader.py b/tasks/0124_739_124739657_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0124_739_124739657_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/0124_739_124739657_qa_1/tests/test.sh b/tasks/0124_739_124739657_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0124_739_124739657_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/0125_045_125045351_qa_4/environment/Dockerfile b/tasks/0125_045_125045351_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0125_045_125045351_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0125_045_125045351_qa_4/environment/pull_bucket.py b/tasks/0125_045_125045351_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0125_045_125045351_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/0125_045_125045351_qa_4/tests/grader.py b/tasks/0125_045_125045351_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0125_045_125045351_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/0125_045_125045351_qa_4/tests/test.sh b/tasks/0125_045_125045351_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0125_045_125045351_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/0125_045_125045351_qa_5/environment/Dockerfile b/tasks/0125_045_125045351_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0125_045_125045351_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0125_045_125045351_qa_5/environment/pull_bucket.py b/tasks/0125_045_125045351_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0125_045_125045351_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/0125_045_125045351_qa_5/tests/grader.py b/tasks/0125_045_125045351_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0125_045_125045351_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/0125_045_125045351_qa_5/tests/test.sh b/tasks/0125_045_125045351_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0125_045_125045351_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/0128_245_128245432_qa_2/environment/Dockerfile b/tasks/0128_245_128245432_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0128_245_128245432_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0128_245_128245432_qa_2/environment/pull_bucket.py b/tasks/0128_245_128245432_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0128_245_128245432_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/0128_245_128245432_qa_2/tests/grader.py b/tasks/0128_245_128245432_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0128_245_128245432_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/0128_245_128245432_qa_2/tests/test.sh b/tasks/0128_245_128245432_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0128_245_128245432_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/0130_870_130870201_qa_1/environment/Dockerfile b/tasks/0130_870_130870201_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0130_870_130870201_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0130_870_130870201_qa_1/environment/pull_bucket.py b/tasks/0130_870_130870201_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0130_870_130870201_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/0130_870_130870201_qa_1/tests/grader.py b/tasks/0130_870_130870201_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0130_870_130870201_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/0130_870_130870201_qa_1/tests/test.sh b/tasks/0130_870_130870201_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0130_870_130870201_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/0130_890_130890369_qa_2/environment/Dockerfile b/tasks/0130_890_130890369_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0130_890_130890369_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0130_890_130890369_qa_2/environment/pull_bucket.py b/tasks/0130_890_130890369_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0130_890_130890369_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/0130_890_130890369_qa_2/tests/grader.py b/tasks/0130_890_130890369_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0130_890_130890369_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/0130_890_130890369_qa_2/tests/test.sh b/tasks/0130_890_130890369_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0130_890_130890369_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/0131_609_131609730_qa_1/environment/Dockerfile b/tasks/0131_609_131609730_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0131_609_131609730_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0131_609_131609730_qa_1/environment/pull_bucket.py b/tasks/0131_609_131609730_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0131_609_131609730_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/0131_609_131609730_qa_1/tests/grader.py b/tasks/0131_609_131609730_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0131_609_131609730_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/0131_609_131609730_qa_1/tests/test.sh b/tasks/0131_609_131609730_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0131_609_131609730_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/0133_078_133078833_qa_1/environment/Dockerfile b/tasks/0133_078_133078833_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0133_078_133078833_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0133_078_133078833_qa_1/environment/pull_bucket.py b/tasks/0133_078_133078833_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0133_078_133078833_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/0133_078_133078833_qa_1/tests/grader.py b/tasks/0133_078_133078833_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0133_078_133078833_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/0133_078_133078833_qa_1/tests/test.sh b/tasks/0133_078_133078833_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0133_078_133078833_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/0133_909_133909373_qa_3/environment/Dockerfile b/tasks/0133_909_133909373_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0133_909_133909373_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0133_909_133909373_qa_3/environment/pull_bucket.py b/tasks/0133_909_133909373_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0133_909_133909373_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/0133_909_133909373_qa_3/tests/grader.py b/tasks/0133_909_133909373_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0133_909_133909373_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/0133_909_133909373_qa_3/tests/test.sh b/tasks/0133_909_133909373_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0133_909_133909373_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/0134_941_134941943_qa_1/environment/Dockerfile b/tasks/0134_941_134941943_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0134_941_134941943_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0134_941_134941943_qa_1/environment/pull_bucket.py b/tasks/0134_941_134941943_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0134_941_134941943_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/0134_941_134941943_qa_1/tests/grader.py b/tasks/0134_941_134941943_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0134_941_134941943_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/0134_941_134941943_qa_1/tests/test.sh b/tasks/0134_941_134941943_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0134_941_134941943_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/0135_674_135674700_qa_2/environment/Dockerfile b/tasks/0135_674_135674700_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0135_674_135674700_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0135_674_135674700_qa_2/environment/pull_bucket.py b/tasks/0135_674_135674700_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0135_674_135674700_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/0135_674_135674700_qa_2/tests/grader.py b/tasks/0135_674_135674700_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0135_674_135674700_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/0135_674_135674700_qa_2/tests/test.sh b/tasks/0135_674_135674700_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0135_674_135674700_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/0135_720_135720396_qa_5/environment/Dockerfile b/tasks/0135_720_135720396_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0135_720_135720396_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0135_720_135720396_qa_5/environment/pull_bucket.py b/tasks/0135_720_135720396_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0135_720_135720396_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/0135_720_135720396_qa_5/tests/grader.py b/tasks/0135_720_135720396_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0135_720_135720396_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/0135_720_135720396_qa_5/tests/test.sh b/tasks/0135_720_135720396_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0135_720_135720396_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/0135_740_135740732_qa_2/environment/Dockerfile b/tasks/0135_740_135740732_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0135_740_135740732_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0135_740_135740732_qa_2/environment/pull_bucket.py b/tasks/0135_740_135740732_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0135_740_135740732_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/0135_740_135740732_qa_2/tests/grader.py b/tasks/0135_740_135740732_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0135_740_135740732_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/0135_740_135740732_qa_2/tests/test.sh b/tasks/0135_740_135740732_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0135_740_135740732_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/0135_920_135920645_qa_4/environment/Dockerfile b/tasks/0135_920_135920645_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0135_920_135920645_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0135_920_135920645_qa_4/environment/pull_bucket.py b/tasks/0135_920_135920645_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0135_920_135920645_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/0135_920_135920645_qa_4/tests/grader.py b/tasks/0135_920_135920645_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0135_920_135920645_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/0135_920_135920645_qa_4/tests/test.sh b/tasks/0135_920_135920645_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0135_920_135920645_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/0136_242_136242885_qa_2/environment/Dockerfile b/tasks/0136_242_136242885_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0136_242_136242885_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0136_242_136242885_qa_2/environment/pull_bucket.py b/tasks/0136_242_136242885_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0136_242_136242885_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/0136_242_136242885_qa_2/tests/grader.py b/tasks/0136_242_136242885_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0136_242_136242885_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/0136_242_136242885_qa_2/tests/test.sh b/tasks/0136_242_136242885_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0136_242_136242885_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/0137_769_137769141_qa_3/environment/Dockerfile b/tasks/0137_769_137769141_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0137_769_137769141_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0137_769_137769141_qa_3/environment/pull_bucket.py b/tasks/0137_769_137769141_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0137_769_137769141_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/0137_769_137769141_qa_3/tests/grader.py b/tasks/0137_769_137769141_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0137_769_137769141_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/0137_769_137769141_qa_3/tests/test.sh b/tasks/0137_769_137769141_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0137_769_137769141_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/0137_769_137769141_qa_4/environment/Dockerfile b/tasks/0137_769_137769141_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0137_769_137769141_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0137_769_137769141_qa_4/environment/pull_bucket.py b/tasks/0137_769_137769141_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0137_769_137769141_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/0137_769_137769141_qa_4/tests/grader.py b/tasks/0137_769_137769141_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0137_769_137769141_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/0137_769_137769141_qa_4/tests/test.sh b/tasks/0137_769_137769141_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0137_769_137769141_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/0138_684_138684554_qa_2/environment/Dockerfile b/tasks/0138_684_138684554_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0138_684_138684554_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0138_684_138684554_qa_2/environment/pull_bucket.py b/tasks/0138_684_138684554_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0138_684_138684554_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_684_138684554_qa_2/tests/grader.py b/tasks/0138_684_138684554_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0138_684_138684554_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_684_138684554_qa_2/tests/test.sh b/tasks/0138_684_138684554_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0138_684_138684554_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/0138_755_138755530_qa_2/environment/Dockerfile b/tasks/0138_755_138755530_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0138_755_138755530_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0138_755_138755530_qa_2/environment/pull_bucket.py b/tasks/0138_755_138755530_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0138_755_138755530_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_755_138755530_qa_2/tests/grader.py b/tasks/0138_755_138755530_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0138_755_138755530_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_755_138755530_qa_2/tests/test.sh b/tasks/0138_755_138755530_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0138_755_138755530_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