diff --git a/tasks/0000_435_435800_qa_4/environment/Dockerfile b/tasks/0000_435_435800_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0000_435_435800_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0000_435_435800_qa_4/environment/pull_bucket.py b/tasks/0000_435_435800_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0000_435_435800_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_435_435800_qa_4/tests/grader.py b/tasks/0000_435_435800_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0000_435_435800_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_435_435800_qa_4/tests/test.sh b/tasks/0000_435_435800_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0000_435_435800_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_455_455476_qa_5/environment/Dockerfile b/tasks/0000_455_455476_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0000_455_455476_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0000_455_455476_qa_5/environment/pull_bucket.py b/tasks/0000_455_455476_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0000_455_455476_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_455_455476_qa_5/tests/grader.py b/tasks/0000_455_455476_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0000_455_455476_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_455_455476_qa_5/tests/test.sh b/tasks/0000_455_455476_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0000_455_455476_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_672_672627_qa_2/environment/Dockerfile b/tasks/0000_672_672627_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0000_672_672627_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0000_672_672627_qa_2/environment/pull_bucket.py b/tasks/0000_672_672627_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0000_672_672627_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_672_672627_qa_2/tests/grader.py b/tasks/0000_672_672627_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0000_672_672627_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_672_672627_qa_2/tests/test.sh b/tasks/0000_672_672627_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0000_672_672627_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_746_746224_qa_4/environment/Dockerfile b/tasks/0000_746_746224_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0000_746_746224_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0000_746_746224_qa_4/environment/pull_bucket.py b/tasks/0000_746_746224_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0000_746_746224_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_746_746224_qa_4/tests/grader.py b/tasks/0000_746_746224_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0000_746_746224_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_746_746224_qa_4/tests/test.sh b/tasks/0000_746_746224_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0000_746_746224_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_816_816225_qa_3/environment/Dockerfile b/tasks/0000_816_816225_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0000_816_816225_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0000_816_816225_qa_3/environment/pull_bucket.py b/tasks/0000_816_816225_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0000_816_816225_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_816_816225_qa_3/tests/grader.py b/tasks/0000_816_816225_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0000_816_816225_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_816_816225_qa_3/tests/test.sh b/tasks/0000_816_816225_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0000_816_816225_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_827_827640_qa_3/environment/Dockerfile b/tasks/0000_827_827640_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0000_827_827640_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0000_827_827640_qa_3/environment/pull_bucket.py b/tasks/0000_827_827640_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0000_827_827640_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_827_827640_qa_3/tests/grader.py b/tasks/0000_827_827640_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0000_827_827640_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_827_827640_qa_3/tests/test.sh b/tasks/0000_827_827640_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0000_827_827640_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_072_1072607_qa_3/environment/Dockerfile b/tasks/0001_072_1072607_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_072_1072607_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_072_1072607_qa_3/environment/pull_bucket.py b/tasks/0001_072_1072607_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_072_1072607_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_072_1072607_qa_3/tests/grader.py b/tasks/0001_072_1072607_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_072_1072607_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_072_1072607_qa_3/tests/test.sh b/tasks/0001_072_1072607_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_072_1072607_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_079_1079149_qa_2/environment/Dockerfile b/tasks/0001_079_1079149_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_079_1079149_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_079_1079149_qa_2/environment/pull_bucket.py b/tasks/0001_079_1079149_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_079_1079149_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_079_1079149_qa_2/tests/grader.py b/tasks/0001_079_1079149_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_079_1079149_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_079_1079149_qa_2/tests/test.sh b/tasks/0001_079_1079149_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_079_1079149_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_090_1090831_qa_3/environment/Dockerfile b/tasks/0001_090_1090831_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_090_1090831_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_090_1090831_qa_3/environment/pull_bucket.py b/tasks/0001_090_1090831_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_090_1090831_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_090_1090831_qa_3/tests/grader.py b/tasks/0001_090_1090831_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_090_1090831_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_090_1090831_qa_3/tests/test.sh b/tasks/0001_090_1090831_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_090_1090831_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_155_1155013_qa_2/environment/Dockerfile b/tasks/0001_155_1155013_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_155_1155013_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_155_1155013_qa_2/environment/pull_bucket.py b/tasks/0001_155_1155013_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_155_1155013_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_155_1155013_qa_2/tests/grader.py b/tasks/0001_155_1155013_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_155_1155013_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_155_1155013_qa_2/tests/test.sh b/tasks/0001_155_1155013_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_155_1155013_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_349_1349978_qa_4/environment/Dockerfile b/tasks/0001_349_1349978_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_349_1349978_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_349_1349978_qa_4/environment/pull_bucket.py b/tasks/0001_349_1349978_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_349_1349978_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_349_1349978_qa_4/tests/grader.py b/tasks/0001_349_1349978_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_349_1349978_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_349_1349978_qa_4/tests/test.sh b/tasks/0001_349_1349978_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_349_1349978_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_351_1351211_qa_2/environment/Dockerfile b/tasks/0001_351_1351211_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_351_1351211_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_351_1351211_qa_2/environment/pull_bucket.py b/tasks/0001_351_1351211_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_351_1351211_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_351_1351211_qa_2/tests/grader.py b/tasks/0001_351_1351211_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_351_1351211_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_351_1351211_qa_2/tests/test.sh b/tasks/0001_351_1351211_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_351_1351211_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_367_1367483_qa_4/environment/Dockerfile b/tasks/0001_367_1367483_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_367_1367483_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_367_1367483_qa_4/environment/pull_bucket.py b/tasks/0001_367_1367483_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_367_1367483_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_367_1367483_qa_4/tests/grader.py b/tasks/0001_367_1367483_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_367_1367483_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_367_1367483_qa_4/tests/test.sh b/tasks/0001_367_1367483_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_367_1367483_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_487_1487950_qa_3/environment/Dockerfile b/tasks/0001_487_1487950_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_487_1487950_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_487_1487950_qa_3/environment/pull_bucket.py b/tasks/0001_487_1487950_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_487_1487950_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_487_1487950_qa_3/tests/grader.py b/tasks/0001_487_1487950_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_487_1487950_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_487_1487950_qa_3/tests/test.sh b/tasks/0001_487_1487950_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_487_1487950_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_531_1531776_qa_2/environment/Dockerfile b/tasks/0001_531_1531776_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_531_1531776_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_531_1531776_qa_2/environment/pull_bucket.py b/tasks/0001_531_1531776_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_531_1531776_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_531_1531776_qa_2/tests/grader.py b/tasks/0001_531_1531776_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_531_1531776_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_531_1531776_qa_2/tests/test.sh b/tasks/0001_531_1531776_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_531_1531776_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_580_1580621_qa_2/environment/Dockerfile b/tasks/0001_580_1580621_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_580_1580621_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_580_1580621_qa_2/environment/pull_bucket.py b/tasks/0001_580_1580621_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_580_1580621_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_580_1580621_qa_2/tests/grader.py b/tasks/0001_580_1580621_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_580_1580621_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_580_1580621_qa_2/tests/test.sh b/tasks/0001_580_1580621_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_580_1580621_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_580_1580621_qa_4/environment/Dockerfile b/tasks/0001_580_1580621_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_580_1580621_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_580_1580621_qa_4/environment/pull_bucket.py b/tasks/0001_580_1580621_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_580_1580621_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_580_1580621_qa_4/tests/grader.py b/tasks/0001_580_1580621_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_580_1580621_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_580_1580621_qa_4/tests/test.sh b/tasks/0001_580_1580621_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_580_1580621_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_640_1640467_qa_2/environment/Dockerfile b/tasks/0001_640_1640467_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_640_1640467_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_640_1640467_qa_2/environment/pull_bucket.py b/tasks/0001_640_1640467_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_640_1640467_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_640_1640467_qa_2/tests/grader.py b/tasks/0001_640_1640467_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_640_1640467_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_640_1640467_qa_2/tests/test.sh b/tasks/0001_640_1640467_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_640_1640467_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_672_1672543_qa_4/environment/Dockerfile b/tasks/0001_672_1672543_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_672_1672543_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_672_1672543_qa_4/environment/pull_bucket.py b/tasks/0001_672_1672543_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_672_1672543_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_672_1672543_qa_4/tests/grader.py b/tasks/0001_672_1672543_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_672_1672543_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_672_1672543_qa_4/tests/test.sh b/tasks/0001_672_1672543_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_672_1672543_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_754_1754320_qa_2/environment/Dockerfile b/tasks/0001_754_1754320_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_754_1754320_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_754_1754320_qa_2/environment/pull_bucket.py b/tasks/0001_754_1754320_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_754_1754320_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_754_1754320_qa_2/tests/grader.py b/tasks/0001_754_1754320_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_754_1754320_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_754_1754320_qa_2/tests/test.sh b/tasks/0001_754_1754320_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_754_1754320_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_825_1825877_qa_5/environment/Dockerfile b/tasks/0001_825_1825877_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_825_1825877_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_825_1825877_qa_5/environment/pull_bucket.py b/tasks/0001_825_1825877_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_825_1825877_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_825_1825877_qa_5/tests/grader.py b/tasks/0001_825_1825877_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_825_1825877_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_825_1825877_qa_5/tests/test.sh b/tasks/0001_825_1825877_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_825_1825877_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_888_1888068_qa_2/environment/Dockerfile b/tasks/0001_888_1888068_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_888_1888068_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_888_1888068_qa_2/environment/pull_bucket.py b/tasks/0001_888_1888068_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_888_1888068_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_888_1888068_qa_2/tests/grader.py b/tasks/0001_888_1888068_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_888_1888068_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_888_1888068_qa_2/tests/test.sh b/tasks/0001_888_1888068_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_888_1888068_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_991_1991376_qa_4/environment/Dockerfile b/tasks/0001_991_1991376_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_991_1991376_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_991_1991376_qa_4/environment/pull_bucket.py b/tasks/0001_991_1991376_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_991_1991376_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_991_1991376_qa_4/tests/grader.py b/tasks/0001_991_1991376_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_991_1991376_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_991_1991376_qa_4/tests/test.sh b/tasks/0001_991_1991376_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_991_1991376_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_991_1991376_qa_5/environment/Dockerfile b/tasks/0001_991_1991376_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_991_1991376_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_991_1991376_qa_5/environment/pull_bucket.py b/tasks/0001_991_1991376_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_991_1991376_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_991_1991376_qa_5/tests/grader.py b/tasks/0001_991_1991376_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0001_991_1991376_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_991_1991376_qa_5/tests/test.sh b/tasks/0001_991_1991376_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_991_1991376_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/0002_093_2093580_qa_1/environment/Dockerfile b/tasks/0002_093_2093580_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0002_093_2093580_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0002_093_2093580_qa_1/environment/pull_bucket.py b/tasks/0002_093_2093580_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0002_093_2093580_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/0002_093_2093580_qa_1/tests/grader.py b/tasks/0002_093_2093580_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0002_093_2093580_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/0002_093_2093580_qa_1/tests/test.sh b/tasks/0002_093_2093580_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0002_093_2093580_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/0002_094_2094789_qa_1/environment/Dockerfile b/tasks/0002_094_2094789_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0002_094_2094789_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0002_094_2094789_qa_1/environment/pull_bucket.py b/tasks/0002_094_2094789_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0002_094_2094789_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/0002_094_2094789_qa_1/tests/grader.py b/tasks/0002_094_2094789_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0002_094_2094789_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/0002_094_2094789_qa_1/tests/test.sh b/tasks/0002_094_2094789_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0002_094_2094789_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/0002_335_2335686_qa_2/environment/Dockerfile b/tasks/0002_335_2335686_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0002_335_2335686_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0002_335_2335686_qa_2/environment/pull_bucket.py b/tasks/0002_335_2335686_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0002_335_2335686_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/0002_335_2335686_qa_2/tests/grader.py b/tasks/0002_335_2335686_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0002_335_2335686_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/0002_335_2335686_qa_2/tests/test.sh b/tasks/0002_335_2335686_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0002_335_2335686_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/0011_054_11054618_qa_1/environment/Dockerfile b/tasks/0011_054_11054618_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0011_054_11054618_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0011_054_11054618_qa_1/environment/pull_bucket.py b/tasks/0011_054_11054618_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0011_054_11054618_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/0011_054_11054618_qa_1/tests/grader.py b/tasks/0011_054_11054618_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0011_054_11054618_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/0011_054_11054618_qa_1/tests/test.sh b/tasks/0011_054_11054618_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0011_054_11054618_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/0011_506_11506450_qa_4/environment/Dockerfile b/tasks/0011_506_11506450_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0011_506_11506450_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0011_506_11506450_qa_4/environment/pull_bucket.py b/tasks/0011_506_11506450_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0011_506_11506450_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/0011_506_11506450_qa_4/tests/grader.py b/tasks/0011_506_11506450_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0011_506_11506450_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/0011_506_11506450_qa_4/tests/test.sh b/tasks/0011_506_11506450_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0011_506_11506450_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/0011_821_11821121_qa_2/environment/Dockerfile b/tasks/0011_821_11821121_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0011_821_11821121_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0011_821_11821121_qa_2/environment/pull_bucket.py b/tasks/0011_821_11821121_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0011_821_11821121_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_821_11821121_qa_2/tests/grader.py b/tasks/0011_821_11821121_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0011_821_11821121_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_821_11821121_qa_2/tests/test.sh b/tasks/0011_821_11821121_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0011_821_11821121_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/0011_842_11842614_qa_2/environment/Dockerfile b/tasks/0011_842_11842614_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0011_842_11842614_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0011_842_11842614_qa_2/environment/pull_bucket.py b/tasks/0011_842_11842614_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0011_842_11842614_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_842_11842614_qa_2/tests/grader.py b/tasks/0011_842_11842614_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0011_842_11842614_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_842_11842614_qa_2/tests/test.sh b/tasks/0011_842_11842614_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0011_842_11842614_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_075_12075481_qa_5/environment/Dockerfile b/tasks/0012_075_12075481_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0012_075_12075481_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0012_075_12075481_qa_5/environment/pull_bucket.py b/tasks/0012_075_12075481_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0012_075_12075481_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/0012_075_12075481_qa_5/tests/grader.py b/tasks/0012_075_12075481_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0012_075_12075481_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/0012_075_12075481_qa_5/tests/test.sh b/tasks/0012_075_12075481_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0012_075_12075481_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/0012_689_12689524_qa_2/environment/Dockerfile b/tasks/0012_689_12689524_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0012_689_12689524_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0012_689_12689524_qa_2/environment/pull_bucket.py b/tasks/0012_689_12689524_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0012_689_12689524_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_689_12689524_qa_2/tests/grader.py b/tasks/0012_689_12689524_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0012_689_12689524_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_689_12689524_qa_2/tests/test.sh b/tasks/0012_689_12689524_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0012_689_12689524_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_689_12689524_qa_4/environment/Dockerfile b/tasks/0012_689_12689524_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0012_689_12689524_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0012_689_12689524_qa_4/environment/pull_bucket.py b/tasks/0012_689_12689524_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0012_689_12689524_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_689_12689524_qa_4/tests/grader.py b/tasks/0012_689_12689524_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0012_689_12689524_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_689_12689524_qa_4/tests/test.sh b/tasks/0012_689_12689524_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0012_689_12689524_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_341_14341598_qa_1/environment/Dockerfile b/tasks/0014_341_14341598_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0014_341_14341598_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0014_341_14341598_qa_1/environment/pull_bucket.py b/tasks/0014_341_14341598_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0014_341_14341598_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_341_14341598_qa_1/tests/grader.py b/tasks/0014_341_14341598_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0014_341_14341598_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_341_14341598_qa_1/tests/test.sh b/tasks/0014_341_14341598_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0014_341_14341598_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_952_14952543_qa_1/environment/Dockerfile b/tasks/0014_952_14952543_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0014_952_14952543_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0014_952_14952543_qa_1/environment/pull_bucket.py b/tasks/0014_952_14952543_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0014_952_14952543_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_952_14952543_qa_1/tests/grader.py b/tasks/0014_952_14952543_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0014_952_14952543_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_952_14952543_qa_1/tests/test.sh b/tasks/0014_952_14952543_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0014_952_14952543_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_135_16135360_qa_3/environment/Dockerfile b/tasks/0016_135_16135360_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0016_135_16135360_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0016_135_16135360_qa_3/environment/pull_bucket.py b/tasks/0016_135_16135360_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0016_135_16135360_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_135_16135360_qa_3/tests/grader.py b/tasks/0016_135_16135360_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0016_135_16135360_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_135_16135360_qa_3/tests/test.sh b/tasks/0016_135_16135360_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0016_135_16135360_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/0016_567_16567793_qa_5/environment/Dockerfile b/tasks/0016_567_16567793_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0016_567_16567793_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0016_567_16567793_qa_5/environment/pull_bucket.py b/tasks/0016_567_16567793_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0016_567_16567793_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/0016_567_16567793_qa_5/tests/grader.py b/tasks/0016_567_16567793_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0016_567_16567793_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/0016_567_16567793_qa_5/tests/test.sh b/tasks/0016_567_16567793_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0016_567_16567793_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/0019_978_19978878_qa_3/environment/Dockerfile b/tasks/0019_978_19978878_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0019_978_19978878_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0019_978_19978878_qa_3/environment/pull_bucket.py b/tasks/0019_978_19978878_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0019_978_19978878_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/0019_978_19978878_qa_3/tests/grader.py b/tasks/0019_978_19978878_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0019_978_19978878_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/0019_978_19978878_qa_3/tests/test.sh b/tasks/0019_978_19978878_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0019_978_19978878_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/0020_764_20764174_qa_3/environment/Dockerfile b/tasks/0020_764_20764174_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0020_764_20764174_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0020_764_20764174_qa_3/environment/pull_bucket.py b/tasks/0020_764_20764174_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0020_764_20764174_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/0020_764_20764174_qa_3/tests/grader.py b/tasks/0020_764_20764174_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0020_764_20764174_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/0020_764_20764174_qa_3/tests/test.sh b/tasks/0020_764_20764174_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0020_764_20764174_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_687_21687757_qa_1/environment/Dockerfile b/tasks/0021_687_21687757_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0021_687_21687757_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0021_687_21687757_qa_1/environment/pull_bucket.py b/tasks/0021_687_21687757_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0021_687_21687757_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_687_21687757_qa_1/tests/grader.py b/tasks/0021_687_21687757_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0021_687_21687757_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_687_21687757_qa_1/tests/test.sh b/tasks/0021_687_21687757_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0021_687_21687757_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/0021_960_21960570_qa_4/environment/Dockerfile b/tasks/0021_960_21960570_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0021_960_21960570_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0021_960_21960570_qa_4/environment/pull_bucket.py b/tasks/0021_960_21960570_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0021_960_21960570_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/0021_960_21960570_qa_4/tests/grader.py b/tasks/0021_960_21960570_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0021_960_21960570_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/0021_960_21960570_qa_4/tests/test.sh b/tasks/0021_960_21960570_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0021_960_21960570_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_580_23580177_qa_2/environment/Dockerfile b/tasks/0023_580_23580177_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0023_580_23580177_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0023_580_23580177_qa_2/environment/pull_bucket.py b/tasks/0023_580_23580177_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0023_580_23580177_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/0023_580_23580177_qa_2/tests/grader.py b/tasks/0023_580_23580177_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0023_580_23580177_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/0023_580_23580177_qa_2/tests/test.sh b/tasks/0023_580_23580177_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0023_580_23580177_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/0023_626_23626093_qa_1/environment/Dockerfile b/tasks/0023_626_23626093_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0023_626_23626093_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0023_626_23626093_qa_1/environment/pull_bucket.py b/tasks/0023_626_23626093_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0023_626_23626093_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_626_23626093_qa_1/tests/grader.py b/tasks/0023_626_23626093_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0023_626_23626093_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_626_23626093_qa_1/tests/test.sh b/tasks/0023_626_23626093_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0023_626_23626093_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/0023_990_23990837_qa_5/environment/Dockerfile b/tasks/0023_990_23990837_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0023_990_23990837_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0023_990_23990837_qa_5/environment/pull_bucket.py b/tasks/0023_990_23990837_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0023_990_23990837_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/0023_990_23990837_qa_5/tests/grader.py b/tasks/0023_990_23990837_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0023_990_23990837_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/0023_990_23990837_qa_5/tests/test.sh b/tasks/0023_990_23990837_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0023_990_23990837_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/0024_658_24658460_qa_4/environment/Dockerfile b/tasks/0024_658_24658460_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0024_658_24658460_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0024_658_24658460_qa_4/environment/pull_bucket.py b/tasks/0024_658_24658460_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0024_658_24658460_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/0024_658_24658460_qa_4/tests/grader.py b/tasks/0024_658_24658460_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0024_658_24658460_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/0024_658_24658460_qa_4/tests/test.sh b/tasks/0024_658_24658460_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0024_658_24658460_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/0025_273_25273223_qa_4/environment/Dockerfile b/tasks/0025_273_25273223_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0025_273_25273223_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0025_273_25273223_qa_4/environment/pull_bucket.py b/tasks/0025_273_25273223_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0025_273_25273223_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_273_25273223_qa_4/tests/grader.py b/tasks/0025_273_25273223_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0025_273_25273223_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_273_25273223_qa_4/tests/test.sh b/tasks/0025_273_25273223_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0025_273_25273223_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/0025_744_25744450_qa_1/environment/Dockerfile b/tasks/0025_744_25744450_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0025_744_25744450_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0025_744_25744450_qa_1/environment/pull_bucket.py b/tasks/0025_744_25744450_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0025_744_25744450_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/0025_744_25744450_qa_1/tests/grader.py b/tasks/0025_744_25744450_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0025_744_25744450_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/0025_744_25744450_qa_1/tests/test.sh b/tasks/0025_744_25744450_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0025_744_25744450_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/0026_141_26141545_qa_5/environment/Dockerfile b/tasks/0026_141_26141545_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0026_141_26141545_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0026_141_26141545_qa_5/environment/pull_bucket.py b/tasks/0026_141_26141545_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0026_141_26141545_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/0026_141_26141545_qa_5/tests/grader.py b/tasks/0026_141_26141545_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0026_141_26141545_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/0026_141_26141545_qa_5/tests/test.sh b/tasks/0026_141_26141545_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0026_141_26141545_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/0026_319_26319225_qa_1/environment/Dockerfile b/tasks/0026_319_26319225_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0026_319_26319225_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0026_319_26319225_qa_1/environment/pull_bucket.py b/tasks/0026_319_26319225_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0026_319_26319225_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_319_26319225_qa_1/tests/grader.py b/tasks/0026_319_26319225_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0026_319_26319225_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_319_26319225_qa_1/tests/test.sh b/tasks/0026_319_26319225_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0026_319_26319225_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_492_28492741_qa_1/environment/Dockerfile b/tasks/0028_492_28492741_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0028_492_28492741_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0028_492_28492741_qa_1/environment/pull_bucket.py b/tasks/0028_492_28492741_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0028_492_28492741_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/0028_492_28492741_qa_1/tests/grader.py b/tasks/0028_492_28492741_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0028_492_28492741_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/0028_492_28492741_qa_1/tests/test.sh b/tasks/0028_492_28492741_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0028_492_28492741_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_938_28938151_qa_5/environment/Dockerfile b/tasks/0028_938_28938151_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0028_938_28938151_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0028_938_28938151_qa_5/environment/pull_bucket.py b/tasks/0028_938_28938151_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0028_938_28938151_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/0028_938_28938151_qa_5/tests/grader.py b/tasks/0028_938_28938151_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0028_938_28938151_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/0028_938_28938151_qa_5/tests/test.sh b/tasks/0028_938_28938151_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0028_938_28938151_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/0029_200_29200364_qa_1/environment/Dockerfile b/tasks/0029_200_29200364_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0029_200_29200364_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0029_200_29200364_qa_1/environment/pull_bucket.py b/tasks/0029_200_29200364_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0029_200_29200364_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_200_29200364_qa_1/tests/grader.py b/tasks/0029_200_29200364_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0029_200_29200364_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_200_29200364_qa_1/tests/test.sh b/tasks/0029_200_29200364_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0029_200_29200364_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_245_29245024_qa_1/environment/Dockerfile b/tasks/0029_245_29245024_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0029_245_29245024_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0029_245_29245024_qa_1/environment/pull_bucket.py b/tasks/0029_245_29245024_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0029_245_29245024_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_245_29245024_qa_1/tests/grader.py b/tasks/0029_245_29245024_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0029_245_29245024_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_245_29245024_qa_1/tests/test.sh b/tasks/0029_245_29245024_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0029_245_29245024_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_991_30991339_qa_3/environment/Dockerfile b/tasks/0030_991_30991339_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0030_991_30991339_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0030_991_30991339_qa_3/environment/pull_bucket.py b/tasks/0030_991_30991339_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0030_991_30991339_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/0030_991_30991339_qa_3/tests/grader.py b/tasks/0030_991_30991339_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0030_991_30991339_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/0030_991_30991339_qa_3/tests/test.sh b/tasks/0030_991_30991339_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0030_991_30991339_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/0031_128_31128554_qa_2/environment/Dockerfile b/tasks/0031_128_31128554_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0031_128_31128554_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0031_128_31128554_qa_2/environment/pull_bucket.py b/tasks/0031_128_31128554_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0031_128_31128554_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_128_31128554_qa_2/tests/grader.py b/tasks/0031_128_31128554_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0031_128_31128554_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_128_31128554_qa_2/tests/test.sh b/tasks/0031_128_31128554_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0031_128_31128554_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_128_31128554_qa_5/environment/Dockerfile b/tasks/0031_128_31128554_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0031_128_31128554_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0031_128_31128554_qa_5/environment/pull_bucket.py b/tasks/0031_128_31128554_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0031_128_31128554_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/0031_128_31128554_qa_5/tests/grader.py b/tasks/0031_128_31128554_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0031_128_31128554_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/0031_128_31128554_qa_5/tests/test.sh b/tasks/0031_128_31128554_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0031_128_31128554_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_954_31954799_qa_2/environment/Dockerfile b/tasks/0031_954_31954799_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0031_954_31954799_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0031_954_31954799_qa_2/environment/pull_bucket.py b/tasks/0031_954_31954799_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0031_954_31954799_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_954_31954799_qa_2/tests/grader.py b/tasks/0031_954_31954799_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0031_954_31954799_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_954_31954799_qa_2/tests/test.sh b/tasks/0031_954_31954799_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0031_954_31954799_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_071_32071401_qa_5/environment/Dockerfile b/tasks/0032_071_32071401_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0032_071_32071401_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0032_071_32071401_qa_5/environment/pull_bucket.py b/tasks/0032_071_32071401_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0032_071_32071401_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/0032_071_32071401_qa_5/tests/grader.py b/tasks/0032_071_32071401_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0032_071_32071401_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/0032_071_32071401_qa_5/tests/test.sh b/tasks/0032_071_32071401_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0032_071_32071401_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/0032_337_32337163_qa_1/environment/Dockerfile b/tasks/0032_337_32337163_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0032_337_32337163_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0032_337_32337163_qa_1/environment/pull_bucket.py b/tasks/0032_337_32337163_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0032_337_32337163_qa_1/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0032_337_32337163_qa_1/tests/grader.py b/tasks/0032_337_32337163_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0032_337_32337163_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/0032_337_32337163_qa_1/tests/test.sh b/tasks/0032_337_32337163_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0032_337_32337163_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_734_32734784_qa_3/environment/Dockerfile b/tasks/0032_734_32734784_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0032_734_32734784_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0032_734_32734784_qa_3/environment/pull_bucket.py b/tasks/0032_734_32734784_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0032_734_32734784_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/0032_734_32734784_qa_3/tests/grader.py b/tasks/0032_734_32734784_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0032_734_32734784_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/0032_734_32734784_qa_3/tests/test.sh b/tasks/0032_734_32734784_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0032_734_32734784_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_273_33273125_qa_5/environment/Dockerfile b/tasks/0033_273_33273125_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0033_273_33273125_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0033_273_33273125_qa_5/environment/pull_bucket.py b/tasks/0033_273_33273125_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0033_273_33273125_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/0033_273_33273125_qa_5/tests/grader.py b/tasks/0033_273_33273125_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0033_273_33273125_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/0033_273_33273125_qa_5/tests/test.sh b/tasks/0033_273_33273125_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0033_273_33273125_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/0033_423_33423582_qa_4/environment/Dockerfile b/tasks/0033_423_33423582_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0033_423_33423582_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0033_423_33423582_qa_4/environment/pull_bucket.py b/tasks/0033_423_33423582_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0033_423_33423582_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/0033_423_33423582_qa_4/tests/grader.py b/tasks/0033_423_33423582_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0033_423_33423582_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/0033_423_33423582_qa_4/tests/test.sh b/tasks/0033_423_33423582_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0033_423_33423582_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/0033_726_33726120_qa_2/environment/Dockerfile b/tasks/0033_726_33726120_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0033_726_33726120_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0033_726_33726120_qa_2/environment/pull_bucket.py b/tasks/0033_726_33726120_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0033_726_33726120_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/0033_726_33726120_qa_2/tests/grader.py b/tasks/0033_726_33726120_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0033_726_33726120_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/0033_726_33726120_qa_2/tests/test.sh b/tasks/0033_726_33726120_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0033_726_33726120_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_726_33726120_qa_5/environment/Dockerfile b/tasks/0033_726_33726120_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0033_726_33726120_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0033_726_33726120_qa_5/environment/pull_bucket.py b/tasks/0033_726_33726120_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0033_726_33726120_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/0033_726_33726120_qa_5/tests/grader.py b/tasks/0033_726_33726120_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0033_726_33726120_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/0033_726_33726120_qa_5/tests/test.sh b/tasks/0033_726_33726120_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0033_726_33726120_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_773_34773515_qa_3/environment/Dockerfile b/tasks/0034_773_34773515_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0034_773_34773515_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0034_773_34773515_qa_3/environment/pull_bucket.py b/tasks/0034_773_34773515_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0034_773_34773515_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_773_34773515_qa_3/tests/grader.py b/tasks/0034_773_34773515_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0034_773_34773515_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_773_34773515_qa_3/tests/test.sh b/tasks/0034_773_34773515_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0034_773_34773515_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/0035_121_35121535_qa_1/environment/Dockerfile b/tasks/0035_121_35121535_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0035_121_35121535_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0035_121_35121535_qa_1/environment/pull_bucket.py b/tasks/0035_121_35121535_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0035_121_35121535_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/0035_121_35121535_qa_1/tests/grader.py b/tasks/0035_121_35121535_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0035_121_35121535_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/0035_121_35121535_qa_1/tests/test.sh b/tasks/0035_121_35121535_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0035_121_35121535_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/0035_336_35336797_qa_4/environment/Dockerfile b/tasks/0035_336_35336797_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0035_336_35336797_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0035_336_35336797_qa_4/environment/pull_bucket.py b/tasks/0035_336_35336797_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0035_336_35336797_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_336_35336797_qa_4/tests/grader.py b/tasks/0035_336_35336797_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0035_336_35336797_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_336_35336797_qa_4/tests/test.sh b/tasks/0035_336_35336797_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0035_336_35336797_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_546_35546963_qa_4/environment/Dockerfile b/tasks/0035_546_35546963_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0035_546_35546963_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0035_546_35546963_qa_4/environment/pull_bucket.py b/tasks/0035_546_35546963_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0035_546_35546963_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_546_35546963_qa_4/tests/grader.py b/tasks/0035_546_35546963_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0035_546_35546963_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_546_35546963_qa_4/tests/test.sh b/tasks/0035_546_35546963_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0035_546_35546963_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_745_35745803_qa_1/environment/Dockerfile b/tasks/0035_745_35745803_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0035_745_35745803_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0035_745_35745803_qa_1/environment/pull_bucket.py b/tasks/0035_745_35745803_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0035_745_35745803_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/0035_745_35745803_qa_1/tests/grader.py b/tasks/0035_745_35745803_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0035_745_35745803_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/0035_745_35745803_qa_1/tests/test.sh b/tasks/0035_745_35745803_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0035_745_35745803_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/0035_921_35921172_qa_5/environment/Dockerfile b/tasks/0035_921_35921172_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0035_921_35921172_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0035_921_35921172_qa_5/environment/pull_bucket.py b/tasks/0035_921_35921172_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0035_921_35921172_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/0035_921_35921172_qa_5/tests/grader.py b/tasks/0035_921_35921172_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0035_921_35921172_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/0035_921_35921172_qa_5/tests/test.sh b/tasks/0035_921_35921172_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0035_921_35921172_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_305_36305200_qa_3/environment/Dockerfile b/tasks/0036_305_36305200_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0036_305_36305200_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0036_305_36305200_qa_3/environment/pull_bucket.py b/tasks/0036_305_36305200_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0036_305_36305200_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/0036_305_36305200_qa_3/tests/grader.py b/tasks/0036_305_36305200_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0036_305_36305200_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/0036_305_36305200_qa_3/tests/test.sh b/tasks/0036_305_36305200_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0036_305_36305200_qa_3/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0038_165_38165504_qa_3/environment/Dockerfile b/tasks/0038_165_38165504_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0038_165_38165504_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0038_165_38165504_qa_3/environment/pull_bucket.py b/tasks/0038_165_38165504_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0038_165_38165504_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/0038_165_38165504_qa_3/tests/grader.py b/tasks/0038_165_38165504_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0038_165_38165504_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/0038_165_38165504_qa_3/tests/test.sh b/tasks/0038_165_38165504_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0038_165_38165504_qa_3/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0038_439_38439618_qa_5/environment/Dockerfile b/tasks/0038_439_38439618_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0038_439_38439618_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0038_439_38439618_qa_5/environment/pull_bucket.py b/tasks/0038_439_38439618_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0038_439_38439618_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_439_38439618_qa_5/tests/grader.py b/tasks/0038_439_38439618_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0038_439_38439618_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_439_38439618_qa_5/tests/test.sh b/tasks/0038_439_38439618_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0038_439_38439618_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/0038_606_38606903_qa_3/environment/Dockerfile b/tasks/0038_606_38606903_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0038_606_38606903_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0038_606_38606903_qa_3/environment/pull_bucket.py b/tasks/0038_606_38606903_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0038_606_38606903_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/0038_606_38606903_qa_3/tests/grader.py b/tasks/0038_606_38606903_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0038_606_38606903_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/0038_606_38606903_qa_3/tests/test.sh b/tasks/0038_606_38606903_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0038_606_38606903_qa_3/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0038_821_38821925_qa_1/environment/Dockerfile b/tasks/0038_821_38821925_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0038_821_38821925_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0038_821_38821925_qa_1/environment/pull_bucket.py b/tasks/0038_821_38821925_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0038_821_38821925_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/0038_821_38821925_qa_1/tests/grader.py b/tasks/0038_821_38821925_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0038_821_38821925_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/0038_821_38821925_qa_1/tests/test.sh b/tasks/0038_821_38821925_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0038_821_38821925_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_884_38884588_qa_5/environment/Dockerfile b/tasks/0038_884_38884588_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0038_884_38884588_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0038_884_38884588_qa_5/environment/pull_bucket.py b/tasks/0038_884_38884588_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0038_884_38884588_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_884_38884588_qa_5/tests/grader.py b/tasks/0038_884_38884588_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0038_884_38884588_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_884_38884588_qa_5/tests/test.sh b/tasks/0038_884_38884588_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0038_884_38884588_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_008_39008775_qa_5/environment/Dockerfile b/tasks/0039_008_39008775_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0039_008_39008775_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0039_008_39008775_qa_5/environment/pull_bucket.py b/tasks/0039_008_39008775_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0039_008_39008775_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/0039_008_39008775_qa_5/tests/grader.py b/tasks/0039_008_39008775_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0039_008_39008775_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/0039_008_39008775_qa_5/tests/test.sh b/tasks/0039_008_39008775_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0039_008_39008775_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_782_39782405_qa_2/environment/Dockerfile b/tasks/0039_782_39782405_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0039_782_39782405_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0039_782_39782405_qa_2/environment/pull_bucket.py b/tasks/0039_782_39782405_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0039_782_39782405_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_782_39782405_qa_2/tests/grader.py b/tasks/0039_782_39782405_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0039_782_39782405_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_782_39782405_qa_2/tests/test.sh b/tasks/0039_782_39782405_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0039_782_39782405_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_794_39794889_qa_1/environment/Dockerfile b/tasks/0039_794_39794889_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0039_794_39794889_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0039_794_39794889_qa_1/environment/pull_bucket.py b/tasks/0039_794_39794889_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0039_794_39794889_qa_1/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0039_794_39794889_qa_1/tests/grader.py b/tasks/0039_794_39794889_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0039_794_39794889_qa_1/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + try: + with open("/workdir/.n_tool_calls") as fh: + return int(fh.read().strip()) + except (OSError, ValueError): + pass + raw = os.environ.get("N_TOOL_CALLS") + if raw is not None: + try: + return int(str(raw).strip()) + except ValueError: + return None + return None + + +def _tool_efficiency(n_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0039_794_39794889_qa_1/tests/test.sh b/tasks/0039_794_39794889_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0039_794_39794889_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/0039_908_39908824_qa_4/environment/Dockerfile b/tasks/0039_908_39908824_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0039_908_39908824_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0039_908_39908824_qa_4/environment/pull_bucket.py b/tasks/0039_908_39908824_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0039_908_39908824_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/0039_908_39908824_qa_4/tests/grader.py b/tasks/0039_908_39908824_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0039_908_39908824_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/0039_908_39908824_qa_4/tests/test.sh b/tasks/0039_908_39908824_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0039_908_39908824_qa_4/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0040_916_40916847_qa_3/environment/Dockerfile b/tasks/0040_916_40916847_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0040_916_40916847_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0040_916_40916847_qa_3/environment/pull_bucket.py b/tasks/0040_916_40916847_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0040_916_40916847_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_916_40916847_qa_3/tests/grader.py b/tasks/0040_916_40916847_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0040_916_40916847_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_916_40916847_qa_3/tests/test.sh b/tasks/0040_916_40916847_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0040_916_40916847_qa_3/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0041_015_41015677_qa_2/environment/Dockerfile b/tasks/0041_015_41015677_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0041_015_41015677_qa_2/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_2/environment/pull_bucket.py b/tasks/0041_015_41015677_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0041_015_41015677_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_015_41015677_qa_2/tests/grader.py b/tasks/0041_015_41015677_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0041_015_41015677_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_015_41015677_qa_2/tests/test.sh b/tasks/0041_015_41015677_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0041_015_41015677_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_216_41216352_qa_3/environment/Dockerfile b/tasks/0041_216_41216352_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0041_216_41216352_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0041_216_41216352_qa_3/environment/pull_bucket.py b/tasks/0041_216_41216352_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0041_216_41216352_qa_3/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0041_216_41216352_qa_3/tests/grader.py b/tasks/0041_216_41216352_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0041_216_41216352_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/0041_216_41216352_qa_3/tests/test.sh b/tasks/0041_216_41216352_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0041_216_41216352_qa_3/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0041_818_41818748_qa_3/environment/Dockerfile b/tasks/0041_818_41818748_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0041_818_41818748_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0041_818_41818748_qa_3/environment/pull_bucket.py b/tasks/0041_818_41818748_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0041_818_41818748_qa_3/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0041_818_41818748_qa_3/tests/grader.py b/tasks/0041_818_41818748_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0041_818_41818748_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/0041_818_41818748_qa_3/tests/test.sh b/tasks/0041_818_41818748_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0041_818_41818748_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_049_42049242_qa_1/environment/Dockerfile b/tasks/0042_049_42049242_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0042_049_42049242_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0042_049_42049242_qa_1/environment/pull_bucket.py b/tasks/0042_049_42049242_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0042_049_42049242_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_049_42049242_qa_1/tests/grader.py b/tasks/0042_049_42049242_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0042_049_42049242_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_049_42049242_qa_1/tests/test.sh b/tasks/0042_049_42049242_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0042_049_42049242_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_106_42106983_qa_5/environment/Dockerfile b/tasks/0042_106_42106983_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0042_106_42106983_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0042_106_42106983_qa_5/environment/pull_bucket.py b/tasks/0042_106_42106983_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0042_106_42106983_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_106_42106983_qa_5/tests/grader.py b/tasks/0042_106_42106983_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0042_106_42106983_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_106_42106983_qa_5/tests/test.sh b/tasks/0042_106_42106983_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0042_106_42106983_qa_5/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0042_446_42446239_qa_1/environment/Dockerfile b/tasks/0042_446_42446239_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0042_446_42446239_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0042_446_42446239_qa_1/environment/pull_bucket.py b/tasks/0042_446_42446239_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0042_446_42446239_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_446_42446239_qa_1/tests/grader.py b/tasks/0042_446_42446239_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0042_446_42446239_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_446_42446239_qa_1/tests/test.sh b/tasks/0042_446_42446239_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0042_446_42446239_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/0043_069_43069626_qa_4/environment/Dockerfile b/tasks/0043_069_43069626_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0043_069_43069626_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0043_069_43069626_qa_4/environment/pull_bucket.py b/tasks/0043_069_43069626_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0043_069_43069626_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_069_43069626_qa_4/tests/grader.py b/tasks/0043_069_43069626_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0043_069_43069626_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_069_43069626_qa_4/tests/test.sh b/tasks/0043_069_43069626_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0043_069_43069626_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_524_43524264_qa_1/environment/Dockerfile b/tasks/0043_524_43524264_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0043_524_43524264_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0043_524_43524264_qa_1/environment/pull_bucket.py b/tasks/0043_524_43524264_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0043_524_43524264_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_524_43524264_qa_1/tests/grader.py b/tasks/0043_524_43524264_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0043_524_43524264_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_524_43524264_qa_1/tests/test.sh b/tasks/0043_524_43524264_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0043_524_43524264_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/0043_829_43829102_qa_2/environment/Dockerfile b/tasks/0043_829_43829102_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0043_829_43829102_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0043_829_43829102_qa_2/environment/pull_bucket.py b/tasks/0043_829_43829102_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0043_829_43829102_qa_2/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0043_829_43829102_qa_2/tests/grader.py b/tasks/0043_829_43829102_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0043_829_43829102_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/0043_829_43829102_qa_2/tests/test.sh b/tasks/0043_829_43829102_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0043_829_43829102_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/0044_393_44393884_qa_1/environment/Dockerfile b/tasks/0044_393_44393884_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0044_393_44393884_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0044_393_44393884_qa_1/environment/pull_bucket.py b/tasks/0044_393_44393884_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0044_393_44393884_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_393_44393884_qa_1/tests/grader.py b/tasks/0044_393_44393884_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0044_393_44393884_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_393_44393884_qa_1/tests/test.sh b/tasks/0044_393_44393884_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0044_393_44393884_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_136_45136493_qa_3/environment/Dockerfile b/tasks/0045_136_45136493_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0045_136_45136493_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0045_136_45136493_qa_3/environment/pull_bucket.py b/tasks/0045_136_45136493_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0045_136_45136493_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_136_45136493_qa_3/tests/grader.py b/tasks/0045_136_45136493_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0045_136_45136493_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_136_45136493_qa_3/tests/test.sh b/tasks/0045_136_45136493_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0045_136_45136493_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_409_45409591_qa_1/environment/Dockerfile b/tasks/0045_409_45409591_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0045_409_45409591_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0045_409_45409591_qa_1/environment/pull_bucket.py b/tasks/0045_409_45409591_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0045_409_45409591_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_409_45409591_qa_1/tests/grader.py b/tasks/0045_409_45409591_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0045_409_45409591_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_409_45409591_qa_1/tests/test.sh b/tasks/0045_409_45409591_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0045_409_45409591_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_178_46178687_qa_4/environment/Dockerfile b/tasks/0046_178_46178687_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0046_178_46178687_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0046_178_46178687_qa_4/environment/pull_bucket.py b/tasks/0046_178_46178687_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0046_178_46178687_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_178_46178687_qa_4/tests/grader.py b/tasks/0046_178_46178687_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0046_178_46178687_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_178_46178687_qa_4/tests/test.sh b/tasks/0046_178_46178687_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0046_178_46178687_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_282_46282379_qa_2/environment/Dockerfile b/tasks/0046_282_46282379_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0046_282_46282379_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0046_282_46282379_qa_2/environment/pull_bucket.py b/tasks/0046_282_46282379_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0046_282_46282379_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/0046_282_46282379_qa_2/tests/grader.py b/tasks/0046_282_46282379_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0046_282_46282379_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/0046_282_46282379_qa_2/tests/test.sh b/tasks/0046_282_46282379_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0046_282_46282379_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/0047_398_47398075_qa_2/environment/Dockerfile b/tasks/0047_398_47398075_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0047_398_47398075_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0047_398_47398075_qa_2/environment/pull_bucket.py b/tasks/0047_398_47398075_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0047_398_47398075_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_398_47398075_qa_2/tests/grader.py b/tasks/0047_398_47398075_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0047_398_47398075_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_398_47398075_qa_2/tests/test.sh b/tasks/0047_398_47398075_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0047_398_47398075_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/0047_398_47398075_qa_5/environment/Dockerfile b/tasks/0047_398_47398075_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0047_398_47398075_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0047_398_47398075_qa_5/environment/pull_bucket.py b/tasks/0047_398_47398075_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0047_398_47398075_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/0047_398_47398075_qa_5/tests/grader.py b/tasks/0047_398_47398075_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0047_398_47398075_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/0047_398_47398075_qa_5/tests/test.sh b/tasks/0047_398_47398075_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0047_398_47398075_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/0050_306_50306022_qa_3/environment/Dockerfile b/tasks/0050_306_50306022_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0050_306_50306022_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0050_306_50306022_qa_3/environment/pull_bucket.py b/tasks/0050_306_50306022_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0050_306_50306022_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/0050_306_50306022_qa_3/tests/grader.py b/tasks/0050_306_50306022_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0050_306_50306022_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/0050_306_50306022_qa_3/tests/test.sh b/tasks/0050_306_50306022_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0050_306_50306022_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/0051_852_51852671_qa_1/environment/Dockerfile b/tasks/0051_852_51852671_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0051_852_51852671_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0051_852_51852671_qa_1/environment/pull_bucket.py b/tasks/0051_852_51852671_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0051_852_51852671_qa_1/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0051_852_51852671_qa_1/tests/grader.py b/tasks/0051_852_51852671_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0051_852_51852671_qa_1/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + try: + with open("/workdir/.n_tool_calls") as fh: + return int(fh.read().strip()) + except (OSError, ValueError): + pass + raw = os.environ.get("N_TOOL_CALLS") + if raw is not None: + try: + return int(str(raw).strip()) + except ValueError: + return None + return None + + +def _tool_efficiency(n_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0051_852_51852671_qa_1/tests/test.sh b/tasks/0051_852_51852671_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0051_852_51852671_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/0052_512_52512591_qa_4/environment/Dockerfile b/tasks/0052_512_52512591_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0052_512_52512591_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0052_512_52512591_qa_4/environment/pull_bucket.py b/tasks/0052_512_52512591_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0052_512_52512591_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_512_52512591_qa_4/tests/grader.py b/tasks/0052_512_52512591_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0052_512_52512591_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_512_52512591_qa_4/tests/test.sh b/tasks/0052_512_52512591_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0052_512_52512591_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_587_52587517_qa_3/environment/Dockerfile b/tasks/0052_587_52587517_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0052_587_52587517_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0052_587_52587517_qa_3/environment/pull_bucket.py b/tasks/0052_587_52587517_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0052_587_52587517_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_587_52587517_qa_3/tests/grader.py b/tasks/0052_587_52587517_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0052_587_52587517_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_587_52587517_qa_3/tests/test.sh b/tasks/0052_587_52587517_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0052_587_52587517_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_587_52587517_qa_4/environment/Dockerfile b/tasks/0052_587_52587517_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0052_587_52587517_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0052_587_52587517_qa_4/environment/pull_bucket.py b/tasks/0052_587_52587517_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0052_587_52587517_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_587_52587517_qa_4/tests/grader.py b/tasks/0052_587_52587517_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0052_587_52587517_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_587_52587517_qa_4/tests/test.sh b/tasks/0052_587_52587517_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0052_587_52587517_qa_4/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0053_327_53327790_qa_3/environment/Dockerfile b/tasks/0053_327_53327790_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0053_327_53327790_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0053_327_53327790_qa_3/environment/pull_bucket.py b/tasks/0053_327_53327790_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0053_327_53327790_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/0053_327_53327790_qa_3/tests/grader.py b/tasks/0053_327_53327790_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0053_327_53327790_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/0053_327_53327790_qa_3/tests/test.sh b/tasks/0053_327_53327790_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0053_327_53327790_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_995_53995551_qa_1/environment/Dockerfile b/tasks/0053_995_53995551_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0053_995_53995551_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0053_995_53995551_qa_1/environment/pull_bucket.py b/tasks/0053_995_53995551_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0053_995_53995551_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_995_53995551_qa_1/tests/grader.py b/tasks/0053_995_53995551_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0053_995_53995551_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_995_53995551_qa_1/tests/test.sh b/tasks/0053_995_53995551_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0053_995_53995551_qa_1/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0055_004_55004083_qa_4/environment/Dockerfile b/tasks/0055_004_55004083_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0055_004_55004083_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0055_004_55004083_qa_4/environment/pull_bucket.py b/tasks/0055_004_55004083_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0055_004_55004083_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_004_55004083_qa_4/tests/grader.py b/tasks/0055_004_55004083_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0055_004_55004083_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_004_55004083_qa_4/tests/test.sh b/tasks/0055_004_55004083_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0055_004_55004083_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_391_56391883_qa_4/environment/Dockerfile b/tasks/0056_391_56391883_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0056_391_56391883_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0056_391_56391883_qa_4/environment/pull_bucket.py b/tasks/0056_391_56391883_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0056_391_56391883_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/0056_391_56391883_qa_4/tests/grader.py b/tasks/0056_391_56391883_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0056_391_56391883_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/0056_391_56391883_qa_4/tests/test.sh b/tasks/0056_391_56391883_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0056_391_56391883_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_748_56748033_qa_1/environment/Dockerfile b/tasks/0056_748_56748033_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0056_748_56748033_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0056_748_56748033_qa_1/environment/pull_bucket.py b/tasks/0056_748_56748033_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0056_748_56748033_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/0056_748_56748033_qa_1/tests/grader.py b/tasks/0056_748_56748033_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0056_748_56748033_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/0056_748_56748033_qa_1/tests/test.sh b/tasks/0056_748_56748033_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0056_748_56748033_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/0057_481_57481754_qa_1/environment/Dockerfile b/tasks/0057_481_57481754_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0057_481_57481754_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0057_481_57481754_qa_1/environment/pull_bucket.py b/tasks/0057_481_57481754_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0057_481_57481754_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/0057_481_57481754_qa_1/tests/grader.py b/tasks/0057_481_57481754_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0057_481_57481754_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/0057_481_57481754_qa_1/tests/test.sh b/tasks/0057_481_57481754_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0057_481_57481754_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/0057_721_57721830_qa_1/environment/Dockerfile b/tasks/0057_721_57721830_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0057_721_57721830_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0057_721_57721830_qa_1/environment/pull_bucket.py b/tasks/0057_721_57721830_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0057_721_57721830_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/0057_721_57721830_qa_1/tests/grader.py b/tasks/0057_721_57721830_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0057_721_57721830_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/0057_721_57721830_qa_1/tests/test.sh b/tasks/0057_721_57721830_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0057_721_57721830_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/0059_000_59000863_qa_2/environment/Dockerfile b/tasks/0059_000_59000863_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0059_000_59000863_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0059_000_59000863_qa_2/environment/pull_bucket.py b/tasks/0059_000_59000863_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0059_000_59000863_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/0059_000_59000863_qa_2/tests/grader.py b/tasks/0059_000_59000863_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0059_000_59000863_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/0059_000_59000863_qa_2/tests/test.sh b/tasks/0059_000_59000863_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0059_000_59000863_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/0060_106_60106319_qa_1/environment/Dockerfile b/tasks/0060_106_60106319_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0060_106_60106319_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0060_106_60106319_qa_1/environment/pull_bucket.py b/tasks/0060_106_60106319_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0060_106_60106319_qa_1/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0060_106_60106319_qa_1/tests/grader.py b/tasks/0060_106_60106319_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0060_106_60106319_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/0060_106_60106319_qa_1/tests/test.sh b/tasks/0060_106_60106319_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0060_106_60106319_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/0061_208_61208833_qa_5/environment/Dockerfile b/tasks/0061_208_61208833_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0061_208_61208833_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0061_208_61208833_qa_5/environment/pull_bucket.py b/tasks/0061_208_61208833_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0061_208_61208833_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/0061_208_61208833_qa_5/tests/grader.py b/tasks/0061_208_61208833_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0061_208_61208833_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/0061_208_61208833_qa_5/tests/test.sh b/tasks/0061_208_61208833_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0061_208_61208833_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/0061_353_61353471_qa_1/environment/Dockerfile b/tasks/0061_353_61353471_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0061_353_61353471_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0061_353_61353471_qa_1/environment/pull_bucket.py b/tasks/0061_353_61353471_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0061_353_61353471_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/0061_353_61353471_qa_1/tests/grader.py b/tasks/0061_353_61353471_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0061_353_61353471_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/0061_353_61353471_qa_1/tests/test.sh b/tasks/0061_353_61353471_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0061_353_61353471_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/0061_362_61362835_qa_3/environment/Dockerfile b/tasks/0061_362_61362835_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0061_362_61362835_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0061_362_61362835_qa_3/environment/pull_bucket.py b/tasks/0061_362_61362835_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0061_362_61362835_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/0061_362_61362835_qa_3/tests/grader.py b/tasks/0061_362_61362835_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0061_362_61362835_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/0061_362_61362835_qa_3/tests/test.sh b/tasks/0061_362_61362835_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0061_362_61362835_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_945_62945279_qa_3/environment/Dockerfile b/tasks/0062_945_62945279_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0062_945_62945279_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0062_945_62945279_qa_3/environment/pull_bucket.py b/tasks/0062_945_62945279_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0062_945_62945279_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_945_62945279_qa_3/tests/grader.py b/tasks/0062_945_62945279_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0062_945_62945279_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_945_62945279_qa_3/tests/test.sh b/tasks/0062_945_62945279_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0062_945_62945279_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_973_62973078_qa_1/environment/Dockerfile b/tasks/0062_973_62973078_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0062_973_62973078_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0062_973_62973078_qa_1/environment/pull_bucket.py b/tasks/0062_973_62973078_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0062_973_62973078_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/0062_973_62973078_qa_1/tests/grader.py b/tasks/0062_973_62973078_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0062_973_62973078_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/0062_973_62973078_qa_1/tests/test.sh b/tasks/0062_973_62973078_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0062_973_62973078_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/0063_490_63490471_qa_1/environment/Dockerfile b/tasks/0063_490_63490471_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0063_490_63490471_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0063_490_63490471_qa_1/environment/pull_bucket.py b/tasks/0063_490_63490471_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0063_490_63490471_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_490_63490471_qa_1/tests/grader.py b/tasks/0063_490_63490471_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0063_490_63490471_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_490_63490471_qa_1/tests/test.sh b/tasks/0063_490_63490471_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0063_490_63490471_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_698_64698192_qa_1/environment/Dockerfile b/tasks/0064_698_64698192_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0064_698_64698192_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0064_698_64698192_qa_1/environment/pull_bucket.py b/tasks/0064_698_64698192_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0064_698_64698192_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_698_64698192_qa_1/tests/grader.py b/tasks/0064_698_64698192_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0064_698_64698192_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_698_64698192_qa_1/tests/test.sh b/tasks/0064_698_64698192_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0064_698_64698192_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_766_64766227_qa_2/environment/Dockerfile b/tasks/0064_766_64766227_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0064_766_64766227_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0064_766_64766227_qa_2/environment/pull_bucket.py b/tasks/0064_766_64766227_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0064_766_64766227_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_766_64766227_qa_2/tests/grader.py b/tasks/0064_766_64766227_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0064_766_64766227_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_766_64766227_qa_2/tests/test.sh b/tasks/0064_766_64766227_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0064_766_64766227_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_504_65504512_qa_4/environment/Dockerfile b/tasks/0065_504_65504512_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0065_504_65504512_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0065_504_65504512_qa_4/environment/pull_bucket.py b/tasks/0065_504_65504512_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0065_504_65504512_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_504_65504512_qa_4/tests/grader.py b/tasks/0065_504_65504512_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0065_504_65504512_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_504_65504512_qa_4/tests/test.sh b/tasks/0065_504_65504512_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0065_504_65504512_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_504_65504512_qa_5/environment/Dockerfile b/tasks/0065_504_65504512_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0065_504_65504512_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0065_504_65504512_qa_5/environment/pull_bucket.py b/tasks/0065_504_65504512_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0065_504_65504512_qa_5/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0065_504_65504512_qa_5/tests/grader.py b/tasks/0065_504_65504512_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0065_504_65504512_qa_5/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + try: + with open("/workdir/.n_tool_calls") as fh: + return int(fh.read().strip()) + except (OSError, ValueError): + pass + raw = os.environ.get("N_TOOL_CALLS") + if raw is not None: + try: + return int(str(raw).strip()) + except ValueError: + return None + return None + + +def _tool_efficiency(n_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0065_504_65504512_qa_5/tests/test.sh b/tasks/0065_504_65504512_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0065_504_65504512_qa_5/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0066_107_66107048_qa_2/environment/Dockerfile b/tasks/0066_107_66107048_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0066_107_66107048_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0066_107_66107048_qa_2/environment/pull_bucket.py b/tasks/0066_107_66107048_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0066_107_66107048_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/0066_107_66107048_qa_2/tests/grader.py b/tasks/0066_107_66107048_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0066_107_66107048_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/0066_107_66107048_qa_2/tests/test.sh b/tasks/0066_107_66107048_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0066_107_66107048_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/0067_607_67607384_qa_1/environment/Dockerfile b/tasks/0067_607_67607384_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0067_607_67607384_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0067_607_67607384_qa_1/environment/pull_bucket.py b/tasks/0067_607_67607384_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0067_607_67607384_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/0067_607_67607384_qa_1/tests/grader.py b/tasks/0067_607_67607384_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0067_607_67607384_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/0067_607_67607384_qa_1/tests/test.sh b/tasks/0067_607_67607384_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0067_607_67607384_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/0067_675_67675814_qa_2/environment/Dockerfile b/tasks/0067_675_67675814_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0067_675_67675814_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0067_675_67675814_qa_2/environment/pull_bucket.py b/tasks/0067_675_67675814_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0067_675_67675814_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/0067_675_67675814_qa_2/tests/grader.py b/tasks/0067_675_67675814_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0067_675_67675814_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/0067_675_67675814_qa_2/tests/test.sh b/tasks/0067_675_67675814_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0067_675_67675814_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/0068_405_68405460_qa_4/environment/Dockerfile b/tasks/0068_405_68405460_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0068_405_68405460_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0068_405_68405460_qa_4/environment/pull_bucket.py b/tasks/0068_405_68405460_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0068_405_68405460_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_405_68405460_qa_4/tests/grader.py b/tasks/0068_405_68405460_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0068_405_68405460_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_405_68405460_qa_4/tests/test.sh b/tasks/0068_405_68405460_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0068_405_68405460_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_397_69397859_qa_5/environment/Dockerfile b/tasks/0069_397_69397859_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0069_397_69397859_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0069_397_69397859_qa_5/environment/pull_bucket.py b/tasks/0069_397_69397859_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0069_397_69397859_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_397_69397859_qa_5/tests/grader.py b/tasks/0069_397_69397859_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0069_397_69397859_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_397_69397859_qa_5/tests/test.sh b/tasks/0069_397_69397859_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0069_397_69397859_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/0071_835_71835908_qa_3/environment/Dockerfile b/tasks/0071_835_71835908_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0071_835_71835908_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0071_835_71835908_qa_3/environment/pull_bucket.py b/tasks/0071_835_71835908_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0071_835_71835908_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/0071_835_71835908_qa_3/tests/grader.py b/tasks/0071_835_71835908_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0071_835_71835908_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/0071_835_71835908_qa_3/tests/test.sh b/tasks/0071_835_71835908_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0071_835_71835908_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/0073_529_73529560_qa_5/environment/Dockerfile b/tasks/0073_529_73529560_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0073_529_73529560_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0073_529_73529560_qa_5/environment/pull_bucket.py b/tasks/0073_529_73529560_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0073_529_73529560_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/0073_529_73529560_qa_5/tests/grader.py b/tasks/0073_529_73529560_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0073_529_73529560_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/0073_529_73529560_qa_5/tests/test.sh b/tasks/0073_529_73529560_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0073_529_73529560_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_719_73719424_qa_1/environment/Dockerfile b/tasks/0073_719_73719424_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0073_719_73719424_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0073_719_73719424_qa_1/environment/pull_bucket.py b/tasks/0073_719_73719424_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0073_719_73719424_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/0073_719_73719424_qa_1/tests/grader.py b/tasks/0073_719_73719424_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0073_719_73719424_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/0073_719_73719424_qa_1/tests/test.sh b/tasks/0073_719_73719424_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0073_719_73719424_qa_1/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0074_527_74527162_qa_5/environment/Dockerfile b/tasks/0074_527_74527162_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0074_527_74527162_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0074_527_74527162_qa_5/environment/pull_bucket.py b/tasks/0074_527_74527162_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0074_527_74527162_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/0074_527_74527162_qa_5/tests/grader.py b/tasks/0074_527_74527162_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0074_527_74527162_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/0074_527_74527162_qa_5/tests/test.sh b/tasks/0074_527_74527162_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0074_527_74527162_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/0074_549_74549731_qa_5/environment/Dockerfile b/tasks/0074_549_74549731_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0074_549_74549731_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0074_549_74549731_qa_5/environment/pull_bucket.py b/tasks/0074_549_74549731_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0074_549_74549731_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/0074_549_74549731_qa_5/tests/grader.py b/tasks/0074_549_74549731_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0074_549_74549731_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/0074_549_74549731_qa_5/tests/test.sh b/tasks/0074_549_74549731_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0074_549_74549731_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/0074_776_74776615_qa_1/environment/Dockerfile b/tasks/0074_776_74776615_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0074_776_74776615_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0074_776_74776615_qa_1/environment/pull_bucket.py b/tasks/0074_776_74776615_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0074_776_74776615_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/0074_776_74776615_qa_1/tests/grader.py b/tasks/0074_776_74776615_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0074_776_74776615_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/0074_776_74776615_qa_1/tests/test.sh b/tasks/0074_776_74776615_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0074_776_74776615_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_379_75379398_qa_2/environment/Dockerfile b/tasks/0075_379_75379398_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0075_379_75379398_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0075_379_75379398_qa_2/environment/pull_bucket.py b/tasks/0075_379_75379398_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0075_379_75379398_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/0075_379_75379398_qa_2/tests/grader.py b/tasks/0075_379_75379398_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0075_379_75379398_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/0075_379_75379398_qa_2/tests/test.sh b/tasks/0075_379_75379398_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0075_379_75379398_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/0076_072_76072290_qa_5/environment/Dockerfile b/tasks/0076_072_76072290_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0076_072_76072290_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0076_072_76072290_qa_5/environment/pull_bucket.py b/tasks/0076_072_76072290_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0076_072_76072290_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/0076_072_76072290_qa_5/tests/grader.py b/tasks/0076_072_76072290_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0076_072_76072290_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/0076_072_76072290_qa_5/tests/test.sh b/tasks/0076_072_76072290_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0076_072_76072290_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/0078_900_78900393_qa_5/environment/Dockerfile b/tasks/0078_900_78900393_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0078_900_78900393_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0078_900_78900393_qa_5/environment/pull_bucket.py b/tasks/0078_900_78900393_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0078_900_78900393_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/0078_900_78900393_qa_5/tests/grader.py b/tasks/0078_900_78900393_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0078_900_78900393_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/0078_900_78900393_qa_5/tests/test.sh b/tasks/0078_900_78900393_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0078_900_78900393_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/0080_200_80200515_qa_3/environment/Dockerfile b/tasks/0080_200_80200515_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0080_200_80200515_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0080_200_80200515_qa_3/environment/pull_bucket.py b/tasks/0080_200_80200515_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0080_200_80200515_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_200_80200515_qa_3/tests/grader.py b/tasks/0080_200_80200515_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0080_200_80200515_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_200_80200515_qa_3/tests/test.sh b/tasks/0080_200_80200515_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0080_200_80200515_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/0081_332_81332828_qa_4/environment/Dockerfile b/tasks/0081_332_81332828_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0081_332_81332828_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0081_332_81332828_qa_4/environment/pull_bucket.py b/tasks/0081_332_81332828_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0081_332_81332828_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_332_81332828_qa_4/tests/grader.py b/tasks/0081_332_81332828_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0081_332_81332828_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_332_81332828_qa_4/tests/test.sh b/tasks/0081_332_81332828_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0081_332_81332828_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/0082_302_82302927_qa_3/environment/Dockerfile b/tasks/0082_302_82302927_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0082_302_82302927_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0082_302_82302927_qa_3/environment/pull_bucket.py b/tasks/0082_302_82302927_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0082_302_82302927_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/0082_302_82302927_qa_3/tests/grader.py b/tasks/0082_302_82302927_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0082_302_82302927_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/0082_302_82302927_qa_3/tests/test.sh b/tasks/0082_302_82302927_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0082_302_82302927_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/0082_994_82994330_qa_5/environment/Dockerfile b/tasks/0082_994_82994330_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0082_994_82994330_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0082_994_82994330_qa_5/environment/pull_bucket.py b/tasks/0082_994_82994330_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0082_994_82994330_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/0082_994_82994330_qa_5/tests/grader.py b/tasks/0082_994_82994330_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0082_994_82994330_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/0082_994_82994330_qa_5/tests/test.sh b/tasks/0082_994_82994330_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0082_994_82994330_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/0083_989_83989999_qa_2/environment/Dockerfile b/tasks/0083_989_83989999_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0083_989_83989999_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0083_989_83989999_qa_2/environment/pull_bucket.py b/tasks/0083_989_83989999_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0083_989_83989999_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_989_83989999_qa_2/tests/grader.py b/tasks/0083_989_83989999_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0083_989_83989999_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_989_83989999_qa_2/tests/test.sh b/tasks/0083_989_83989999_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0083_989_83989999_qa_2/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0084_320_84320235_qa_1/environment/Dockerfile b/tasks/0084_320_84320235_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0084_320_84320235_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0084_320_84320235_qa_1/environment/pull_bucket.py b/tasks/0084_320_84320235_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0084_320_84320235_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/0084_320_84320235_qa_1/tests/grader.py b/tasks/0084_320_84320235_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0084_320_84320235_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/0084_320_84320235_qa_1/tests/test.sh b/tasks/0084_320_84320235_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0084_320_84320235_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/0084_737_84737869_qa_2/environment/Dockerfile b/tasks/0084_737_84737869_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0084_737_84737869_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0084_737_84737869_qa_2/environment/pull_bucket.py b/tasks/0084_737_84737869_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0084_737_84737869_qa_2/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0084_737_84737869_qa_2/tests/grader.py b/tasks/0084_737_84737869_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0084_737_84737869_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/0084_737_84737869_qa_2/tests/test.sh b/tasks/0084_737_84737869_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0084_737_84737869_qa_2/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0084_737_84737869_qa_3/environment/Dockerfile b/tasks/0084_737_84737869_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0084_737_84737869_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0084_737_84737869_qa_3/environment/pull_bucket.py b/tasks/0084_737_84737869_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0084_737_84737869_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/0084_737_84737869_qa_3/tests/grader.py b/tasks/0084_737_84737869_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0084_737_84737869_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/0084_737_84737869_qa_3/tests/test.sh b/tasks/0084_737_84737869_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0084_737_84737869_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/0084_900_84900004_qa_1/environment/Dockerfile b/tasks/0084_900_84900004_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0084_900_84900004_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0084_900_84900004_qa_1/environment/pull_bucket.py b/tasks/0084_900_84900004_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0084_900_84900004_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/0084_900_84900004_qa_1/tests/grader.py b/tasks/0084_900_84900004_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0084_900_84900004_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/0084_900_84900004_qa_1/tests/test.sh b/tasks/0084_900_84900004_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0084_900_84900004_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_383_85383242_qa_5/environment/Dockerfile b/tasks/0085_383_85383242_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0085_383_85383242_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0085_383_85383242_qa_5/environment/pull_bucket.py b/tasks/0085_383_85383242_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0085_383_85383242_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_383_85383242_qa_5/tests/grader.py b/tasks/0085_383_85383242_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0085_383_85383242_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_383_85383242_qa_5/tests/test.sh b/tasks/0085_383_85383242_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0085_383_85383242_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_804_85804318_qa_2/environment/Dockerfile b/tasks/0085_804_85804318_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0085_804_85804318_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0085_804_85804318_qa_2/environment/pull_bucket.py b/tasks/0085_804_85804318_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0085_804_85804318_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_804_85804318_qa_2/tests/grader.py b/tasks/0085_804_85804318_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0085_804_85804318_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_804_85804318_qa_2/tests/test.sh b/tasks/0085_804_85804318_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0085_804_85804318_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/0085_804_85804318_qa_3/environment/Dockerfile b/tasks/0085_804_85804318_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0085_804_85804318_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0085_804_85804318_qa_3/environment/pull_bucket.py b/tasks/0085_804_85804318_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0085_804_85804318_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/0085_804_85804318_qa_3/tests/grader.py b/tasks/0085_804_85804318_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0085_804_85804318_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/0085_804_85804318_qa_3/tests/test.sh b/tasks/0085_804_85804318_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0085_804_85804318_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/0085_903_85903605_qa_2/environment/Dockerfile b/tasks/0085_903_85903605_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0085_903_85903605_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0085_903_85903605_qa_2/environment/pull_bucket.py b/tasks/0085_903_85903605_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0085_903_85903605_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_903_85903605_qa_2/tests/grader.py b/tasks/0085_903_85903605_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0085_903_85903605_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_903_85903605_qa_2/tests/test.sh b/tasks/0085_903_85903605_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0085_903_85903605_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/0085_958_85958060_qa_1/environment/Dockerfile b/tasks/0085_958_85958060_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0085_958_85958060_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0085_958_85958060_qa_1/environment/pull_bucket.py b/tasks/0085_958_85958060_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0085_958_85958060_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/0085_958_85958060_qa_1/tests/grader.py b/tasks/0085_958_85958060_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0085_958_85958060_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/0085_958_85958060_qa_1/tests/test.sh b/tasks/0085_958_85958060_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0085_958_85958060_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/0086_271_86271835_qa_1/environment/Dockerfile b/tasks/0086_271_86271835_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0086_271_86271835_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0086_271_86271835_qa_1/environment/pull_bucket.py b/tasks/0086_271_86271835_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0086_271_86271835_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/0086_271_86271835_qa_1/tests/grader.py b/tasks/0086_271_86271835_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0086_271_86271835_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/0086_271_86271835_qa_1/tests/test.sh b/tasks/0086_271_86271835_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0086_271_86271835_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/0086_824_86824902_qa_2/environment/Dockerfile b/tasks/0086_824_86824902_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0086_824_86824902_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0086_824_86824902_qa_2/environment/pull_bucket.py b/tasks/0086_824_86824902_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0086_824_86824902_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/0086_824_86824902_qa_2/tests/grader.py b/tasks/0086_824_86824902_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0086_824_86824902_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/0086_824_86824902_qa_2/tests/test.sh b/tasks/0086_824_86824902_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0086_824_86824902_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/0087_365_87365940_qa_1/environment/Dockerfile b/tasks/0087_365_87365940_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0087_365_87365940_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0087_365_87365940_qa_1/environment/pull_bucket.py b/tasks/0087_365_87365940_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0087_365_87365940_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_365_87365940_qa_1/tests/grader.py b/tasks/0087_365_87365940_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0087_365_87365940_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_365_87365940_qa_1/tests/test.sh b/tasks/0087_365_87365940_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0087_365_87365940_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_867_87867765_qa_4/environment/Dockerfile b/tasks/0087_867_87867765_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0087_867_87867765_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0087_867_87867765_qa_4/environment/pull_bucket.py b/tasks/0087_867_87867765_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0087_867_87867765_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/0087_867_87867765_qa_4/tests/grader.py b/tasks/0087_867_87867765_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0087_867_87867765_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/0087_867_87867765_qa_4/tests/test.sh b/tasks/0087_867_87867765_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0087_867_87867765_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/0087_867_87867765_qa_5/environment/Dockerfile b/tasks/0087_867_87867765_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0087_867_87867765_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0087_867_87867765_qa_5/environment/pull_bucket.py b/tasks/0087_867_87867765_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0087_867_87867765_qa_5/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0087_867_87867765_qa_5/tests/grader.py b/tasks/0087_867_87867765_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0087_867_87867765_qa_5/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + try: + with open("/workdir/.n_tool_calls") as fh: + return int(fh.read().strip()) + except (OSError, ValueError): + pass + raw = os.environ.get("N_TOOL_CALLS") + if raw is not None: + try: + return int(str(raw).strip()) + except ValueError: + return None + return None + + +def _tool_efficiency(n_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0087_867_87867765_qa_5/tests/test.sh b/tasks/0087_867_87867765_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0087_867_87867765_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/0088_720_88720224_qa_1/environment/Dockerfile b/tasks/0088_720_88720224_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0088_720_88720224_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0088_720_88720224_qa_1/environment/pull_bucket.py b/tasks/0088_720_88720224_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0088_720_88720224_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_720_88720224_qa_1/tests/grader.py b/tasks/0088_720_88720224_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0088_720_88720224_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_720_88720224_qa_1/tests/test.sh b/tasks/0088_720_88720224_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0088_720_88720224_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_736_88736093_qa_5/environment/Dockerfile b/tasks/0088_736_88736093_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0088_736_88736093_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0088_736_88736093_qa_5/environment/pull_bucket.py b/tasks/0088_736_88736093_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0088_736_88736093_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/0088_736_88736093_qa_5/tests/grader.py b/tasks/0088_736_88736093_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0088_736_88736093_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/0088_736_88736093_qa_5/tests/test.sh b/tasks/0088_736_88736093_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0088_736_88736093_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/0089_129_89129153_qa_1/environment/Dockerfile b/tasks/0089_129_89129153_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0089_129_89129153_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0089_129_89129153_qa_1/environment/pull_bucket.py b/tasks/0089_129_89129153_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0089_129_89129153_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/0089_129_89129153_qa_1/tests/grader.py b/tasks/0089_129_89129153_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0089_129_89129153_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/0089_129_89129153_qa_1/tests/test.sh b/tasks/0089_129_89129153_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0089_129_89129153_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/0090_587_90587169_qa_2/environment/Dockerfile b/tasks/0090_587_90587169_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0090_587_90587169_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0090_587_90587169_qa_2/environment/pull_bucket.py b/tasks/0090_587_90587169_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0090_587_90587169_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/0090_587_90587169_qa_2/tests/grader.py b/tasks/0090_587_90587169_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0090_587_90587169_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/0090_587_90587169_qa_2/tests/test.sh b/tasks/0090_587_90587169_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0090_587_90587169_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/0092_606_92606348_qa_4/environment/Dockerfile b/tasks/0092_606_92606348_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0092_606_92606348_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0092_606_92606348_qa_4/environment/pull_bucket.py b/tasks/0092_606_92606348_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0092_606_92606348_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/0092_606_92606348_qa_4/tests/grader.py b/tasks/0092_606_92606348_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0092_606_92606348_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/0092_606_92606348_qa_4/tests/test.sh b/tasks/0092_606_92606348_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0092_606_92606348_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/0093_442_93442881_qa_2/environment/Dockerfile b/tasks/0093_442_93442881_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0093_442_93442881_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0093_442_93442881_qa_2/environment/pull_bucket.py b/tasks/0093_442_93442881_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0093_442_93442881_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/0093_442_93442881_qa_2/tests/grader.py b/tasks/0093_442_93442881_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0093_442_93442881_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/0093_442_93442881_qa_2/tests/test.sh b/tasks/0093_442_93442881_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0093_442_93442881_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/0094_116_94116653_qa_2/environment/Dockerfile b/tasks/0094_116_94116653_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0094_116_94116653_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0094_116_94116653_qa_2/environment/pull_bucket.py b/tasks/0094_116_94116653_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0094_116_94116653_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/0094_116_94116653_qa_2/tests/grader.py b/tasks/0094_116_94116653_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0094_116_94116653_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/0094_116_94116653_qa_2/tests/test.sh b/tasks/0094_116_94116653_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0094_116_94116653_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/0094_264_94264953_qa_3/environment/Dockerfile b/tasks/0094_264_94264953_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0094_264_94264953_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0094_264_94264953_qa_3/environment/pull_bucket.py b/tasks/0094_264_94264953_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0094_264_94264953_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/0094_264_94264953_qa_3/tests/grader.py b/tasks/0094_264_94264953_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0094_264_94264953_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/0094_264_94264953_qa_3/tests/test.sh b/tasks/0094_264_94264953_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0094_264_94264953_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/0094_415_94415300_qa_4/environment/Dockerfile b/tasks/0094_415_94415300_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0094_415_94415300_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0094_415_94415300_qa_4/environment/pull_bucket.py b/tasks/0094_415_94415300_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0094_415_94415300_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/0094_415_94415300_qa_4/tests/grader.py b/tasks/0094_415_94415300_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0094_415_94415300_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/0094_415_94415300_qa_4/tests/test.sh b/tasks/0094_415_94415300_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0094_415_94415300_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/0094_540_94540451_qa_2/environment/Dockerfile b/tasks/0094_540_94540451_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0094_540_94540451_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0094_540_94540451_qa_2/environment/pull_bucket.py b/tasks/0094_540_94540451_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0094_540_94540451_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/0094_540_94540451_qa_2/tests/grader.py b/tasks/0094_540_94540451_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0094_540_94540451_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/0094_540_94540451_qa_2/tests/test.sh b/tasks/0094_540_94540451_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0094_540_94540451_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/0095_088_95088024_qa_1/environment/Dockerfile b/tasks/0095_088_95088024_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0095_088_95088024_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0095_088_95088024_qa_1/environment/pull_bucket.py b/tasks/0095_088_95088024_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0095_088_95088024_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/0095_088_95088024_qa_1/tests/grader.py b/tasks/0095_088_95088024_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0095_088_95088024_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/0095_088_95088024_qa_1/tests/test.sh b/tasks/0095_088_95088024_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0095_088_95088024_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_624_95624401_qa_2/environment/Dockerfile b/tasks/0095_624_95624401_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0095_624_95624401_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0095_624_95624401_qa_2/environment/pull_bucket.py b/tasks/0095_624_95624401_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0095_624_95624401_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/0095_624_95624401_qa_2/tests/grader.py b/tasks/0095_624_95624401_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0095_624_95624401_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/0095_624_95624401_qa_2/tests/test.sh b/tasks/0095_624_95624401_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0095_624_95624401_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/0096_765_96765273_qa_4/environment/Dockerfile b/tasks/0096_765_96765273_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0096_765_96765273_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0096_765_96765273_qa_4/environment/pull_bucket.py b/tasks/0096_765_96765273_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0096_765_96765273_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_765_96765273_qa_4/tests/grader.py b/tasks/0096_765_96765273_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0096_765_96765273_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_765_96765273_qa_4/tests/test.sh b/tasks/0096_765_96765273_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0096_765_96765273_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/0097_377_97377124_qa_1/environment/Dockerfile b/tasks/0097_377_97377124_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0097_377_97377124_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0097_377_97377124_qa_1/environment/pull_bucket.py b/tasks/0097_377_97377124_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0097_377_97377124_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/0097_377_97377124_qa_1/tests/grader.py b/tasks/0097_377_97377124_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0097_377_97377124_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/0097_377_97377124_qa_1/tests/test.sh b/tasks/0097_377_97377124_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0097_377_97377124_qa_1/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0097_698_97698987_qa_4/environment/Dockerfile b/tasks/0097_698_97698987_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0097_698_97698987_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0097_698_97698987_qa_4/environment/pull_bucket.py b/tasks/0097_698_97698987_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0097_698_97698987_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/0097_698_97698987_qa_4/tests/grader.py b/tasks/0097_698_97698987_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0097_698_97698987_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/0097_698_97698987_qa_4/tests/test.sh b/tasks/0097_698_97698987_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0097_698_97698987_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/0097_708_97708214_qa_2/environment/Dockerfile b/tasks/0097_708_97708214_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0097_708_97708214_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0097_708_97708214_qa_2/environment/pull_bucket.py b/tasks/0097_708_97708214_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0097_708_97708214_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_708_97708214_qa_2/tests/grader.py b/tasks/0097_708_97708214_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0097_708_97708214_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_708_97708214_qa_2/tests/test.sh b/tasks/0097_708_97708214_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0097_708_97708214_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/0100_631_100631764_qa_3/environment/Dockerfile b/tasks/0100_631_100631764_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0100_631_100631764_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0100_631_100631764_qa_3/environment/pull_bucket.py b/tasks/0100_631_100631764_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0100_631_100631764_qa_3/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0100_631_100631764_qa_3/tests/grader.py b/tasks/0100_631_100631764_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0100_631_100631764_qa_3/tests/grader.py @@ -0,0 +1,257 @@ +"""Shared three-tier grader. + +Used by both runtimes: + * `env/server.py` — inline inside the `final_answer` ORS @tool method + * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py + and invoked with `python3 /tests/grader.py < /workdir/answer.txt` + +Tiers (cheapest → most expensive): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) + 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) + — only invoked if OPENAI_API_KEY is set + +CLI form (used by tests/test.sh): + EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py + → reads predicted answer from stdin + → writes a single float ('1.0' or '0.0') to stdout + → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass + + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + +# Locked in PLAN.md §"Locked decisions" — adapted from +# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py +JUDGE_PROMPT = """You are grading short answers from a data-science agent. +Decide whether the predicted answer is semantically equivalent to the gold answer. + +Rules: +- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. +- For numbers: predicted must match to the last significant figure of the gold + (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). +- Extra surrounding prose is fine if the gold value is clearly stated + (gold "5", predicted "There are 5 distinct categories" -> CORRECT). +- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). +- Parenthetical annotations in the gold are equivalence hints, not required + (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; + gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). +- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% + is CORRECT as long as the core numeric value matches + (gold "21.334% in 2014", predicted "21.334" -> CORRECT; + gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). +- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one + thing (e.g. "which model?"), predicting either listed value is CORRECT. +- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. +- If it commits to a different value -> INCORRECT. + +Question: {question} +Gold answer: {gold} +Predicted answer: {pred} + +Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" + + +@dataclass +class GradeResult: + reward: float + method: str # "exact" | "numeric" | "llm" | "miss" + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str) -> float | None: + if not s: + return None + m = _NUMERIC_RE.search(s.replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _math_verify_match(gold: str, candidate: str) -> bool: + """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. + + Catches equivalences the naive float-parse misses: thousands separators, + fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. + Fails CLOSED — any parse error / prose gold / timeout returns False (never a + false positive). No network, no LLM. + """ + try: + from math_verify import parse, verify + + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: # noqa: BLE001 + return False + + +def _is_clean_number(s: str) -> bool: + """True iff the whole string IS a single number (allowing a leading/trailing + %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. + A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so + the numeric tier must not fire on it (its `_to_float` would grab the leading + '3' and false-positive-match any answer starting with 3).""" + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def grade( + gold: str, + candidate: str, + *, + question: str = "", + reward_mode: str = "", + judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed + judge_model: str | None = None, # noqa: ARG001 + rel_tol: float = 1e-3, + abs_tol: float = 1e-3, +) -> GradeResult: + """Deterministic three-tier match — NO LLM judge. + + exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify + -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). + """ + + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # ── Tier 2: numeric — ONLY when the gold is a single clean number ── + # (compound golds like "Y=3 with 95,293 instances" would otherwise match on + # the leading number; those must go to exact/math_verify, which fail closed). + if reward_mode == "numeric" or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + return GradeResult(1.0, "numeric") + + # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls() -> int | None: + """Number of agent tool calls this rollout, for the efficiency reward. + + Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls + back to the `N_TOOL_CALLS` env var. Returns None if neither is present + (efficiency reward becomes null — the harness didn't report a count). + """ + try: + with open("/workdir/.n_tool_calls") as fh: + return int(fh.read().strip()) + except (OSError, ValueError): + pass + raw = os.environ.get("N_TOOL_CALLS") + if raw is not None: + try: + return int(str(raw).strip()) + except ValueError: + return None + return None + + +def _tool_efficiency(n_calls: int | None) -> float | None: + """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. + + clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B + median was ~9-10 calls). Raw signal — NOT gated on correctness here; the + RL reward combiner decides gating/weights. + """ + if n_calls is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n_calls / budget)) + + +def _tols() -> tuple[float, float]: + """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" + def _f(name: str) -> float: + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + """CLI shim for `tests/test.sh` — env-driven, stdout-only. + + Inputs (via env vars set by Harbor's [verifier.env]): + EXPECTED_ANSWER — the gold + QUESTION — the original question + ATOL / RTOL — per-task numeric tolerances (default 1e-3) + + Predicted answer is read from stdin. + Single float written to stdout. Exit code is always 0. + """ + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + print(f"{result.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", + file=sys.stderr) + return 0 + + +def main_json() -> int: + """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. + + Three named rewards (Harbor's VerifierResult.rewards carries them all): + correctness — 1.0 iff graded answer matches gold, else 0.0 + submission — 1.0 iff a non-empty answer was submitted, else 0.0 + tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown + + No submission -> all three 0. Predicted answer on stdin; JSON to stdout. + """ + import json + + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + print("[grader] no submission -> all rewards 0", file=sys.stderr) + return 0 + + at, rt = _tols() + result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) + n_calls = _tool_calls() + eff = _tool_efficiency(n_calls) + print(json.dumps({ + "correctness": float(result.reward), + "submission": 1.0, + "tool_efficiency": eff, + })) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " + f"correctness={result.reward} method={result.method} " + f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0100_631_100631764_qa_3/tests/test.sh b/tasks/0100_631_100631764_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0100_631_100631764_qa_3/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0100_668_100668614_qa_1/environment/Dockerfile b/tasks/0100_668_100668614_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0100_668_100668614_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0100_668_100668614_qa_1/environment/pull_bucket.py b/tasks/0100_668_100668614_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0100_668_100668614_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/0100_668_100668614_qa_1/tests/grader.py b/tasks/0100_668_100668614_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0100_668_100668614_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/0100_668_100668614_qa_1/tests/test.sh b/tasks/0100_668_100668614_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0100_668_100668614_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/0101_296_101296258_qa_3/environment/Dockerfile b/tasks/0101_296_101296258_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0101_296_101296258_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0101_296_101296258_qa_3/environment/pull_bucket.py b/tasks/0101_296_101296258_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0101_296_101296258_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/0101_296_101296258_qa_3/tests/grader.py b/tasks/0101_296_101296258_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0101_296_101296258_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/0101_296_101296258_qa_3/tests/test.sh b/tasks/0101_296_101296258_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0101_296_101296258_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/0101_866_101866934_qa_4/environment/Dockerfile b/tasks/0101_866_101866934_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0101_866_101866934_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0101_866_101866934_qa_4/environment/pull_bucket.py b/tasks/0101_866_101866934_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0101_866_101866934_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_866_101866934_qa_4/tests/grader.py b/tasks/0101_866_101866934_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0101_866_101866934_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_866_101866934_qa_4/tests/test.sh b/tasks/0101_866_101866934_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0101_866_101866934_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_994_101994234_qa_4/environment/Dockerfile b/tasks/0101_994_101994234_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0101_994_101994234_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0101_994_101994234_qa_4/environment/pull_bucket.py b/tasks/0101_994_101994234_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0101_994_101994234_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_994_101994234_qa_4/tests/grader.py b/tasks/0101_994_101994234_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0101_994_101994234_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_994_101994234_qa_4/tests/test.sh b/tasks/0101_994_101994234_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0101_994_101994234_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_378_102378485_qa_2/environment/Dockerfile b/tasks/0102_378_102378485_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0102_378_102378485_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0102_378_102378485_qa_2/environment/pull_bucket.py b/tasks/0102_378_102378485_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0102_378_102378485_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/0102_378_102378485_qa_2/tests/grader.py b/tasks/0102_378_102378485_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0102_378_102378485_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/0102_378_102378485_qa_2/tests/test.sh b/tasks/0102_378_102378485_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0102_378_102378485_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/0102_401_102401343_qa_1/environment/Dockerfile b/tasks/0102_401_102401343_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0102_401_102401343_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0102_401_102401343_qa_1/environment/pull_bucket.py b/tasks/0102_401_102401343_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0102_401_102401343_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_401_102401343_qa_1/tests/grader.py b/tasks/0102_401_102401343_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0102_401_102401343_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_401_102401343_qa_1/tests/test.sh b/tasks/0102_401_102401343_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0102_401_102401343_qa_1/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0103_884_103884351_qa_1/environment/Dockerfile b/tasks/0103_884_103884351_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0103_884_103884351_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0103_884_103884351_qa_1/environment/pull_bucket.py b/tasks/0103_884_103884351_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0103_884_103884351_qa_1/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0103_884_103884351_qa_1/tests/grader.py b/tasks/0103_884_103884351_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0103_884_103884351_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/0103_884_103884351_qa_1/tests/test.sh b/tasks/0103_884_103884351_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0103_884_103884351_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/0104_138_104138961_qa_3/environment/Dockerfile b/tasks/0104_138_104138961_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0104_138_104138961_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0104_138_104138961_qa_3/environment/pull_bucket.py b/tasks/0104_138_104138961_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0104_138_104138961_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/0104_138_104138961_qa_3/tests/grader.py b/tasks/0104_138_104138961_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0104_138_104138961_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/0104_138_104138961_qa_3/tests/test.sh b/tasks/0104_138_104138961_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0104_138_104138961_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_333_104333921_qa_3/environment/Dockerfile b/tasks/0104_333_104333921_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0104_333_104333921_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0104_333_104333921_qa_3/environment/pull_bucket.py b/tasks/0104_333_104333921_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0104_333_104333921_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/0104_333_104333921_qa_3/tests/grader.py b/tasks/0104_333_104333921_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0104_333_104333921_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/0104_333_104333921_qa_3/tests/test.sh b/tasks/0104_333_104333921_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0104_333_104333921_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_518_104518190_qa_2/environment/Dockerfile b/tasks/0104_518_104518190_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0104_518_104518190_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0104_518_104518190_qa_2/environment/pull_bucket.py b/tasks/0104_518_104518190_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0104_518_104518190_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/0104_518_104518190_qa_2/tests/grader.py b/tasks/0104_518_104518190_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0104_518_104518190_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/0104_518_104518190_qa_2/tests/test.sh b/tasks/0104_518_104518190_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0104_518_104518190_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/0104_567_104567275_qa_5/environment/Dockerfile b/tasks/0104_567_104567275_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0104_567_104567275_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0104_567_104567275_qa_5/environment/pull_bucket.py b/tasks/0104_567_104567275_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0104_567_104567275_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_567_104567275_qa_5/tests/grader.py b/tasks/0104_567_104567275_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0104_567_104567275_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_567_104567275_qa_5/tests/test.sh b/tasks/0104_567_104567275_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0104_567_104567275_qa_5/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0105_052_105052091_qa_2/environment/Dockerfile b/tasks/0105_052_105052091_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0105_052_105052091_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0105_052_105052091_qa_2/environment/pull_bucket.py b/tasks/0105_052_105052091_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0105_052_105052091_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/0105_052_105052091_qa_2/tests/grader.py b/tasks/0105_052_105052091_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0105_052_105052091_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/0105_052_105052091_qa_2/tests/test.sh b/tasks/0105_052_105052091_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0105_052_105052091_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/0106_416_106416910_qa_1/environment/Dockerfile b/tasks/0106_416_106416910_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0106_416_106416910_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0106_416_106416910_qa_1/environment/pull_bucket.py b/tasks/0106_416_106416910_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0106_416_106416910_qa_1/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0106_416_106416910_qa_1/tests/grader.py b/tasks/0106_416_106416910_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0106_416_106416910_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/0106_416_106416910_qa_1/tests/test.sh b/tasks/0106_416_106416910_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0106_416_106416910_qa_1/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0106_477_106477503_qa_4/environment/Dockerfile b/tasks/0106_477_106477503_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0106_477_106477503_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0106_477_106477503_qa_4/environment/pull_bucket.py b/tasks/0106_477_106477503_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0106_477_106477503_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/0106_477_106477503_qa_4/tests/grader.py b/tasks/0106_477_106477503_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0106_477_106477503_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/0106_477_106477503_qa_4/tests/test.sh b/tasks/0106_477_106477503_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0106_477_106477503_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_411_107411800_qa_1/environment/Dockerfile b/tasks/0107_411_107411800_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0107_411_107411800_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0107_411_107411800_qa_1/environment/pull_bucket.py b/tasks/0107_411_107411800_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0107_411_107411800_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_411_107411800_qa_1/tests/grader.py b/tasks/0107_411_107411800_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0107_411_107411800_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_411_107411800_qa_1/tests/test.sh b/tasks/0107_411_107411800_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0107_411_107411800_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/0108_835_108835715_qa_5/environment/Dockerfile b/tasks/0108_835_108835715_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0108_835_108835715_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0108_835_108835715_qa_5/environment/pull_bucket.py b/tasks/0108_835_108835715_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0108_835_108835715_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/0108_835_108835715_qa_5/tests/grader.py b/tasks/0108_835_108835715_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0108_835_108835715_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/0108_835_108835715_qa_5/tests/test.sh b/tasks/0108_835_108835715_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0108_835_108835715_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/0110_445_110445671_qa_4/environment/Dockerfile b/tasks/0110_445_110445671_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0110_445_110445671_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0110_445_110445671_qa_4/environment/pull_bucket.py b/tasks/0110_445_110445671_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0110_445_110445671_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/0110_445_110445671_qa_4/tests/grader.py b/tasks/0110_445_110445671_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0110_445_110445671_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/0110_445_110445671_qa_4/tests/test.sh b/tasks/0110_445_110445671_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0110_445_110445671_qa_4/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0110_890_110890415_qa_2/environment/Dockerfile b/tasks/0110_890_110890415_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0110_890_110890415_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0110_890_110890415_qa_2/environment/pull_bucket.py b/tasks/0110_890_110890415_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0110_890_110890415_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/0110_890_110890415_qa_2/tests/grader.py b/tasks/0110_890_110890415_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0110_890_110890415_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/0110_890_110890415_qa_2/tests/test.sh b/tasks/0110_890_110890415_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0110_890_110890415_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/0110_890_110890415_qa_5/environment/Dockerfile b/tasks/0110_890_110890415_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0110_890_110890415_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0110_890_110890415_qa_5/environment/pull_bucket.py b/tasks/0110_890_110890415_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0110_890_110890415_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/0110_890_110890415_qa_5/tests/grader.py b/tasks/0110_890_110890415_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0110_890_110890415_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/0110_890_110890415_qa_5/tests/test.sh b/tasks/0110_890_110890415_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0110_890_110890415_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/0111_889_111889874_qa_2/environment/Dockerfile b/tasks/0111_889_111889874_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0111_889_111889874_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0111_889_111889874_qa_2/environment/pull_bucket.py b/tasks/0111_889_111889874_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0111_889_111889874_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/0111_889_111889874_qa_2/tests/grader.py b/tasks/0111_889_111889874_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0111_889_111889874_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/0111_889_111889874_qa_2/tests/test.sh b/tasks/0111_889_111889874_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0111_889_111889874_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/0112_515_112515781_qa_1/environment/Dockerfile b/tasks/0112_515_112515781_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0112_515_112515781_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0112_515_112515781_qa_1/environment/pull_bucket.py b/tasks/0112_515_112515781_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0112_515_112515781_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/0112_515_112515781_qa_1/tests/grader.py b/tasks/0112_515_112515781_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0112_515_112515781_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/0112_515_112515781_qa_1/tests/test.sh b/tasks/0112_515_112515781_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0112_515_112515781_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/0112_848_112848989_qa_3/environment/Dockerfile b/tasks/0112_848_112848989_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0112_848_112848989_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0112_848_112848989_qa_3/environment/pull_bucket.py b/tasks/0112_848_112848989_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0112_848_112848989_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/0112_848_112848989_qa_3/tests/grader.py b/tasks/0112_848_112848989_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0112_848_112848989_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/0112_848_112848989_qa_3/tests/test.sh b/tasks/0112_848_112848989_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0112_848_112848989_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_848_112848989_qa_4/environment/Dockerfile b/tasks/0112_848_112848989_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0112_848_112848989_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0112_848_112848989_qa_4/environment/pull_bucket.py b/tasks/0112_848_112848989_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0112_848_112848989_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_848_112848989_qa_4/tests/grader.py b/tasks/0112_848_112848989_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0112_848_112848989_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_848_112848989_qa_4/tests/test.sh b/tasks/0112_848_112848989_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0112_848_112848989_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_167_113167723_qa_2/environment/Dockerfile b/tasks/0113_167_113167723_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0113_167_113167723_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0113_167_113167723_qa_2/environment/pull_bucket.py b/tasks/0113_167_113167723_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0113_167_113167723_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/0113_167_113167723_qa_2/tests/grader.py b/tasks/0113_167_113167723_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0113_167_113167723_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/0113_167_113167723_qa_2/tests/test.sh b/tasks/0113_167_113167723_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0113_167_113167723_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/0113_167_113167723_qa_4/environment/Dockerfile b/tasks/0113_167_113167723_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0113_167_113167723_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0113_167_113167723_qa_4/environment/pull_bucket.py b/tasks/0113_167_113167723_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0113_167_113167723_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/0113_167_113167723_qa_4/tests/grader.py b/tasks/0113_167_113167723_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0113_167_113167723_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/0113_167_113167723_qa_4/tests/test.sh b/tasks/0113_167_113167723_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0113_167_113167723_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_504_113504478_qa_3/environment/Dockerfile b/tasks/0113_504_113504478_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0113_504_113504478_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0113_504_113504478_qa_3/environment/pull_bucket.py b/tasks/0113_504_113504478_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0113_504_113504478_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_504_113504478_qa_3/tests/grader.py b/tasks/0113_504_113504478_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0113_504_113504478_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_504_113504478_qa_3/tests/test.sh b/tasks/0113_504_113504478_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0113_504_113504478_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/0113_504_113504478_qa_5/environment/Dockerfile b/tasks/0113_504_113504478_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0113_504_113504478_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0113_504_113504478_qa_5/environment/pull_bucket.py b/tasks/0113_504_113504478_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0113_504_113504478_qa_5/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0113_504_113504478_qa_5/tests/grader.py b/tasks/0113_504_113504478_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0113_504_113504478_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/0113_504_113504478_qa_5/tests/test.sh b/tasks/0113_504_113504478_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0113_504_113504478_qa_5/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0113_929_113929776_qa_3/environment/Dockerfile b/tasks/0113_929_113929776_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0113_929_113929776_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0113_929_113929776_qa_3/environment/pull_bucket.py b/tasks/0113_929_113929776_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0113_929_113929776_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_929_113929776_qa_3/tests/grader.py b/tasks/0113_929_113929776_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0113_929_113929776_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_929_113929776_qa_3/tests/test.sh b/tasks/0113_929_113929776_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0113_929_113929776_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_063_114063568_qa_3/environment/Dockerfile b/tasks/0114_063_114063568_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0114_063_114063568_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0114_063_114063568_qa_3/environment/pull_bucket.py b/tasks/0114_063_114063568_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0114_063_114063568_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_063_114063568_qa_3/tests/grader.py b/tasks/0114_063_114063568_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0114_063_114063568_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_063_114063568_qa_3/tests/test.sh b/tasks/0114_063_114063568_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0114_063_114063568_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_091_114091161_qa_3/environment/Dockerfile b/tasks/0114_091_114091161_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0114_091_114091161_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0114_091_114091161_qa_3/environment/pull_bucket.py b/tasks/0114_091_114091161_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0114_091_114091161_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_091_114091161_qa_3/tests/grader.py b/tasks/0114_091_114091161_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0114_091_114091161_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_091_114091161_qa_3/tests/test.sh b/tasks/0114_091_114091161_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0114_091_114091161_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_484_114484617_qa_1/environment/Dockerfile b/tasks/0114_484_114484617_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0114_484_114484617_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0114_484_114484617_qa_1/environment/pull_bucket.py b/tasks/0114_484_114484617_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0114_484_114484617_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_484_114484617_qa_1/tests/grader.py b/tasks/0114_484_114484617_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0114_484_114484617_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_484_114484617_qa_1/tests/test.sh b/tasks/0114_484_114484617_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0114_484_114484617_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/0115_422_115422452_qa_4/environment/Dockerfile b/tasks/0115_422_115422452_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0115_422_115422452_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0115_422_115422452_qa_4/environment/pull_bucket.py b/tasks/0115_422_115422452_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0115_422_115422452_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/0115_422_115422452_qa_4/tests/grader.py b/tasks/0115_422_115422452_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0115_422_115422452_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/0115_422_115422452_qa_4/tests/test.sh b/tasks/0115_422_115422452_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0115_422_115422452_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_814_115814701_qa_4/environment/Dockerfile b/tasks/0115_814_115814701_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0115_814_115814701_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0115_814_115814701_qa_4/environment/pull_bucket.py b/tasks/0115_814_115814701_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0115_814_115814701_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/0115_814_115814701_qa_4/tests/grader.py b/tasks/0115_814_115814701_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0115_814_115814701_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/0115_814_115814701_qa_4/tests/test.sh b/tasks/0115_814_115814701_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0115_814_115814701_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/0116_015_116015692_qa_5/environment/Dockerfile b/tasks/0116_015_116015692_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0116_015_116015692_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0116_015_116015692_qa_5/environment/pull_bucket.py b/tasks/0116_015_116015692_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0116_015_116015692_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/0116_015_116015692_qa_5/tests/grader.py b/tasks/0116_015_116015692_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0116_015_116015692_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/0116_015_116015692_qa_5/tests/test.sh b/tasks/0116_015_116015692_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0116_015_116015692_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/0116_026_116026387_qa_5/environment/Dockerfile b/tasks/0116_026_116026387_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0116_026_116026387_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0116_026_116026387_qa_5/environment/pull_bucket.py b/tasks/0116_026_116026387_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0116_026_116026387_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/0116_026_116026387_qa_5/tests/grader.py b/tasks/0116_026_116026387_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0116_026_116026387_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/0116_026_116026387_qa_5/tests/test.sh b/tasks/0116_026_116026387_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0116_026_116026387_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/0116_553_116553968_qa_5/environment/Dockerfile b/tasks/0116_553_116553968_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0116_553_116553968_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0116_553_116553968_qa_5/environment/pull_bucket.py b/tasks/0116_553_116553968_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0116_553_116553968_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/0116_553_116553968_qa_5/tests/grader.py b/tasks/0116_553_116553968_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0116_553_116553968_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/0116_553_116553968_qa_5/tests/test.sh b/tasks/0116_553_116553968_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0116_553_116553968_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/0118_595_118595576_qa_5/environment/Dockerfile b/tasks/0118_595_118595576_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0118_595_118595576_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0118_595_118595576_qa_5/environment/pull_bucket.py b/tasks/0118_595_118595576_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0118_595_118595576_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_595_118595576_qa_5/tests/grader.py b/tasks/0118_595_118595576_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0118_595_118595576_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_595_118595576_qa_5/tests/test.sh b/tasks/0118_595_118595576_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0118_595_118595576_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/0118_607_118607538_qa_2/environment/Dockerfile b/tasks/0118_607_118607538_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0118_607_118607538_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0118_607_118607538_qa_2/environment/pull_bucket.py b/tasks/0118_607_118607538_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0118_607_118607538_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/0118_607_118607538_qa_2/tests/grader.py b/tasks/0118_607_118607538_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0118_607_118607538_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/0118_607_118607538_qa_2/tests/test.sh b/tasks/0118_607_118607538_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0118_607_118607538_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/0118_899_118899556_qa_4/environment/Dockerfile b/tasks/0118_899_118899556_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0118_899_118899556_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0118_899_118899556_qa_4/environment/pull_bucket.py b/tasks/0118_899_118899556_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0118_899_118899556_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/0118_899_118899556_qa_4/tests/grader.py b/tasks/0118_899_118899556_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0118_899_118899556_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/0118_899_118899556_qa_4/tests/test.sh b/tasks/0118_899_118899556_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0118_899_118899556_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/0119_001_119001162_qa_4/environment/Dockerfile b/tasks/0119_001_119001162_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0119_001_119001162_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0119_001_119001162_qa_4/environment/pull_bucket.py b/tasks/0119_001_119001162_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0119_001_119001162_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/0119_001_119001162_qa_4/tests/grader.py b/tasks/0119_001_119001162_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0119_001_119001162_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/0119_001_119001162_qa_4/tests/test.sh b/tasks/0119_001_119001162_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0119_001_119001162_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/0119_018_119018113_qa_3/environment/Dockerfile b/tasks/0119_018_119018113_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0119_018_119018113_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0119_018_119018113_qa_3/environment/pull_bucket.py b/tasks/0119_018_119018113_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0119_018_119018113_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/0119_018_119018113_qa_3/tests/grader.py b/tasks/0119_018_119018113_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0119_018_119018113_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/0119_018_119018113_qa_3/tests/test.sh b/tasks/0119_018_119018113_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0119_018_119018113_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/0119_653_119653509_qa_1/environment/Dockerfile b/tasks/0119_653_119653509_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0119_653_119653509_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0119_653_119653509_qa_1/environment/pull_bucket.py b/tasks/0119_653_119653509_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0119_653_119653509_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_653_119653509_qa_1/tests/grader.py b/tasks/0119_653_119653509_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0119_653_119653509_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_653_119653509_qa_1/tests/test.sh b/tasks/0119_653_119653509_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0119_653_119653509_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/0120_574_120574465_qa_1/environment/Dockerfile b/tasks/0120_574_120574465_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0120_574_120574465_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0120_574_120574465_qa_1/environment/pull_bucket.py b/tasks/0120_574_120574465_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0120_574_120574465_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/0120_574_120574465_qa_1/tests/grader.py b/tasks/0120_574_120574465_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0120_574_120574465_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/0120_574_120574465_qa_1/tests/test.sh b/tasks/0120_574_120574465_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0120_574_120574465_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/0121_988_121988886_qa_5/environment/Dockerfile b/tasks/0121_988_121988886_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0121_988_121988886_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0121_988_121988886_qa_5/environment/pull_bucket.py b/tasks/0121_988_121988886_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0121_988_121988886_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/0121_988_121988886_qa_5/tests/grader.py b/tasks/0121_988_121988886_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0121_988_121988886_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/0121_988_121988886_qa_5/tests/test.sh b/tasks/0121_988_121988886_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0121_988_121988886_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/0122_097_122097207_qa_1/environment/Dockerfile b/tasks/0122_097_122097207_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0122_097_122097207_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0122_097_122097207_qa_1/environment/pull_bucket.py b/tasks/0122_097_122097207_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0122_097_122097207_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/0122_097_122097207_qa_1/tests/grader.py b/tasks/0122_097_122097207_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0122_097_122097207_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/0122_097_122097207_qa_1/tests/test.sh b/tasks/0122_097_122097207_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0122_097_122097207_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/0123_169_123169310_qa_3/environment/Dockerfile b/tasks/0123_169_123169310_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0123_169_123169310_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0123_169_123169310_qa_3/environment/pull_bucket.py b/tasks/0123_169_123169310_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0123_169_123169310_qa_3/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0123_169_123169310_qa_3/tests/grader.py b/tasks/0123_169_123169310_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0123_169_123169310_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/0123_169_123169310_qa_3/tests/test.sh b/tasks/0123_169_123169310_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0123_169_123169310_qa_3/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0123_500_123500011_qa_3/environment/Dockerfile b/tasks/0123_500_123500011_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0123_500_123500011_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0123_500_123500011_qa_3/environment/pull_bucket.py b/tasks/0123_500_123500011_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0123_500_123500011_qa_3/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0123_500_123500011_qa_3/tests/grader.py b/tasks/0123_500_123500011_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0123_500_123500011_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/0123_500_123500011_qa_3/tests/test.sh b/tasks/0123_500_123500011_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0123_500_123500011_qa_3/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0123_500_123500011_qa_5/environment/Dockerfile b/tasks/0123_500_123500011_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0123_500_123500011_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0123_500_123500011_qa_5/environment/pull_bucket.py b/tasks/0123_500_123500011_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0123_500_123500011_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/0123_500_123500011_qa_5/tests/grader.py b/tasks/0123_500_123500011_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0123_500_123500011_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/0123_500_123500011_qa_5/tests/test.sh b/tasks/0123_500_123500011_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0123_500_123500011_qa_5/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0123_535_123535058_qa_4/environment/Dockerfile b/tasks/0123_535_123535058_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0123_535_123535058_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0123_535_123535058_qa_4/environment/pull_bucket.py b/tasks/0123_535_123535058_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0123_535_123535058_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/0123_535_123535058_qa_4/tests/grader.py b/tasks/0123_535_123535058_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0123_535_123535058_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/0123_535_123535058_qa_4/tests/test.sh b/tasks/0123_535_123535058_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0123_535_123535058_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_535_123535058_qa_5/environment/Dockerfile b/tasks/0123_535_123535058_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0123_535_123535058_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0123_535_123535058_qa_5/environment/pull_bucket.py b/tasks/0123_535_123535058_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0123_535_123535058_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/0123_535_123535058_qa_5/tests/grader.py b/tasks/0123_535_123535058_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0123_535_123535058_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/0123_535_123535058_qa_5/tests/test.sh b/tasks/0123_535_123535058_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0123_535_123535058_qa_5/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0123_643_123643083_qa_2/environment/Dockerfile b/tasks/0123_643_123643083_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0123_643_123643083_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0123_643_123643083_qa_2/environment/pull_bucket.py b/tasks/0123_643_123643083_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0123_643_123643083_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/0123_643_123643083_qa_2/tests/grader.py b/tasks/0123_643_123643083_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0123_643_123643083_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/0123_643_123643083_qa_2/tests/test.sh b/tasks/0123_643_123643083_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0123_643_123643083_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/0123_735_123735039_qa_4/environment/Dockerfile b/tasks/0123_735_123735039_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0123_735_123735039_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0123_735_123735039_qa_4/environment/pull_bucket.py b/tasks/0123_735_123735039_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0123_735_123735039_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/0123_735_123735039_qa_4/tests/grader.py b/tasks/0123_735_123735039_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0123_735_123735039_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/0123_735_123735039_qa_4/tests/test.sh b/tasks/0123_735_123735039_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0123_735_123735039_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_735_123735039_qa_5/environment/Dockerfile b/tasks/0123_735_123735039_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0123_735_123735039_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0123_735_123735039_qa_5/environment/pull_bucket.py b/tasks/0123_735_123735039_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0123_735_123735039_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/0123_735_123735039_qa_5/tests/grader.py b/tasks/0123_735_123735039_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0123_735_123735039_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/0123_735_123735039_qa_5/tests/test.sh b/tasks/0123_735_123735039_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0123_735_123735039_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/0124_195_124195561_qa_1/environment/Dockerfile b/tasks/0124_195_124195561_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0124_195_124195561_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0124_195_124195561_qa_1/environment/pull_bucket.py b/tasks/0124_195_124195561_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0124_195_124195561_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_195_124195561_qa_1/tests/grader.py b/tasks/0124_195_124195561_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0124_195_124195561_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_195_124195561_qa_1/tests/test.sh b/tasks/0124_195_124195561_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0124_195_124195561_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_966_124966489_qa_1/environment/Dockerfile b/tasks/0124_966_124966489_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0124_966_124966489_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0124_966_124966489_qa_1/environment/pull_bucket.py b/tasks/0124_966_124966489_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0124_966_124966489_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_966_124966489_qa_1/tests/grader.py b/tasks/0124_966_124966489_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0124_966_124966489_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_966_124966489_qa_1/tests/test.sh b/tasks/0124_966_124966489_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0124_966_124966489_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_252_125252436_qa_3/environment/Dockerfile b/tasks/0125_252_125252436_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0125_252_125252436_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0125_252_125252436_qa_3/environment/pull_bucket.py b/tasks/0125_252_125252436_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0125_252_125252436_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/0125_252_125252436_qa_3/tests/grader.py b/tasks/0125_252_125252436_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0125_252_125252436_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/0125_252_125252436_qa_3/tests/test.sh b/tasks/0125_252_125252436_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0125_252_125252436_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/0125_537_125537786_qa_2/environment/Dockerfile b/tasks/0125_537_125537786_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0125_537_125537786_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0125_537_125537786_qa_2/environment/pull_bucket.py b/tasks/0125_537_125537786_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0125_537_125537786_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/0125_537_125537786_qa_2/tests/grader.py b/tasks/0125_537_125537786_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0125_537_125537786_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/0125_537_125537786_qa_2/tests/test.sh b/tasks/0125_537_125537786_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0125_537_125537786_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/0125_537_125537786_qa_3/environment/Dockerfile b/tasks/0125_537_125537786_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0125_537_125537786_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0125_537_125537786_qa_3/environment/pull_bucket.py b/tasks/0125_537_125537786_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0125_537_125537786_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/0125_537_125537786_qa_3/tests/grader.py b/tasks/0125_537_125537786_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0125_537_125537786_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/0125_537_125537786_qa_3/tests/test.sh b/tasks/0125_537_125537786_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0125_537_125537786_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/0125_537_125537786_qa_4/environment/Dockerfile b/tasks/0125_537_125537786_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0125_537_125537786_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0125_537_125537786_qa_4/environment/pull_bucket.py b/tasks/0125_537_125537786_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0125_537_125537786_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_537_125537786_qa_4/tests/grader.py b/tasks/0125_537_125537786_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0125_537_125537786_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_537_125537786_qa_4/tests/test.sh b/tasks/0125_537_125537786_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0125_537_125537786_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_581_125581362_qa_5/environment/Dockerfile b/tasks/0125_581_125581362_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0125_581_125581362_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0125_581_125581362_qa_5/environment/pull_bucket.py b/tasks/0125_581_125581362_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0125_581_125581362_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_581_125581362_qa_5/tests/grader.py b/tasks/0125_581_125581362_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0125_581_125581362_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_581_125581362_qa_5/tests/test.sh b/tasks/0125_581_125581362_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0125_581_125581362_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/0126_706_126706065_qa_3/environment/Dockerfile b/tasks/0126_706_126706065_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0126_706_126706065_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0126_706_126706065_qa_3/environment/pull_bucket.py b/tasks/0126_706_126706065_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0126_706_126706065_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/0126_706_126706065_qa_3/tests/grader.py b/tasks/0126_706_126706065_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0126_706_126706065_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/0126_706_126706065_qa_3/tests/test.sh b/tasks/0126_706_126706065_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0126_706_126706065_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/0127_323_127323479_qa_2/environment/Dockerfile b/tasks/0127_323_127323479_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0127_323_127323479_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0127_323_127323479_qa_2/environment/pull_bucket.py b/tasks/0127_323_127323479_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0127_323_127323479_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/0127_323_127323479_qa_2/tests/grader.py b/tasks/0127_323_127323479_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0127_323_127323479_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/0127_323_127323479_qa_2/tests/test.sh b/tasks/0127_323_127323479_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0127_323_127323479_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/0127_323_127323479_qa_5/environment/Dockerfile b/tasks/0127_323_127323479_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0127_323_127323479_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0127_323_127323479_qa_5/environment/pull_bucket.py b/tasks/0127_323_127323479_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0127_323_127323479_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/0127_323_127323479_qa_5/tests/grader.py b/tasks/0127_323_127323479_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0127_323_127323479_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/0127_323_127323479_qa_5/tests/test.sh b/tasks/0127_323_127323479_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0127_323_127323479_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/0127_775_127775252_qa_4/environment/Dockerfile b/tasks/0127_775_127775252_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0127_775_127775252_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0127_775_127775252_qa_4/environment/pull_bucket.py b/tasks/0127_775_127775252_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0127_775_127775252_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/0127_775_127775252_qa_4/tests/grader.py b/tasks/0127_775_127775252_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0127_775_127775252_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/0127_775_127775252_qa_4/tests/test.sh b/tasks/0127_775_127775252_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0127_775_127775252_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/0128_435_128435180_qa_3/environment/Dockerfile b/tasks/0128_435_128435180_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0128_435_128435180_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0128_435_128435180_qa_3/environment/pull_bucket.py b/tasks/0128_435_128435180_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0128_435_128435180_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/0128_435_128435180_qa_3/tests/grader.py b/tasks/0128_435_128435180_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0128_435_128435180_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/0128_435_128435180_qa_3/tests/test.sh b/tasks/0128_435_128435180_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0128_435_128435180_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/0130_032_130032784_qa_2/environment/Dockerfile b/tasks/0130_032_130032784_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0130_032_130032784_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0130_032_130032784_qa_2/environment/pull_bucket.py b/tasks/0130_032_130032784_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0130_032_130032784_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_032_130032784_qa_2/tests/grader.py b/tasks/0130_032_130032784_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0130_032_130032784_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_032_130032784_qa_2/tests/test.sh b/tasks/0130_032_130032784_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0130_032_130032784_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_072_131072256_qa_1/environment/Dockerfile b/tasks/0131_072_131072256_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0131_072_131072256_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0131_072_131072256_qa_1/environment/pull_bucket.py b/tasks/0131_072_131072256_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0131_072_131072256_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_072_131072256_qa_1/tests/grader.py b/tasks/0131_072_131072256_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0131_072_131072256_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_072_131072256_qa_1/tests/test.sh b/tasks/0131_072_131072256_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0131_072_131072256_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/0132_151_132151183_qa_1/environment/Dockerfile b/tasks/0132_151_132151183_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0132_151_132151183_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0132_151_132151183_qa_1/environment/pull_bucket.py b/tasks/0132_151_132151183_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0132_151_132151183_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/0132_151_132151183_qa_1/tests/grader.py b/tasks/0132_151_132151183_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0132_151_132151183_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/0132_151_132151183_qa_1/tests/test.sh b/tasks/0132_151_132151183_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0132_151_132151183_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/0132_596_132596500_qa_5/environment/Dockerfile b/tasks/0132_596_132596500_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0132_596_132596500_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0132_596_132596500_qa_5/environment/pull_bucket.py b/tasks/0132_596_132596500_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0132_596_132596500_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/0132_596_132596500_qa_5/tests/grader.py b/tasks/0132_596_132596500_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0132_596_132596500_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/0132_596_132596500_qa_5/tests/test.sh b/tasks/0132_596_132596500_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0132_596_132596500_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/0132_903_132903502_qa_3/environment/Dockerfile b/tasks/0132_903_132903502_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0132_903_132903502_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0132_903_132903502_qa_3/environment/pull_bucket.py b/tasks/0132_903_132903502_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0132_903_132903502_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/0132_903_132903502_qa_3/tests/grader.py b/tasks/0132_903_132903502_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0132_903_132903502_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/0132_903_132903502_qa_3/tests/test.sh b/tasks/0132_903_132903502_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0132_903_132903502_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_109_134109927_qa_3/environment/Dockerfile b/tasks/0134_109_134109927_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0134_109_134109927_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0134_109_134109927_qa_3/environment/pull_bucket.py b/tasks/0134_109_134109927_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0134_109_134109927_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/0134_109_134109927_qa_3/tests/grader.py b/tasks/0134_109_134109927_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0134_109_134109927_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/0134_109_134109927_qa_3/tests/test.sh b/tasks/0134_109_134109927_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0134_109_134109927_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_878_134878027_qa_1/environment/Dockerfile b/tasks/0134_878_134878027_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0134_878_134878027_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0134_878_134878027_qa_1/environment/pull_bucket.py b/tasks/0134_878_134878027_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0134_878_134878027_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_878_134878027_qa_1/tests/grader.py b/tasks/0134_878_134878027_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0134_878_134878027_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_878_134878027_qa_1/tests/test.sh b/tasks/0134_878_134878027_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0134_878_134878027_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_364_135364354_qa_3/environment/Dockerfile b/tasks/0135_364_135364354_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0135_364_135364354_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0135_364_135364354_qa_3/environment/pull_bucket.py b/tasks/0135_364_135364354_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0135_364_135364354_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/0135_364_135364354_qa_3/tests/grader.py b/tasks/0135_364_135364354_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0135_364_135364354_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/0135_364_135364354_qa_3/tests/test.sh b/tasks/0135_364_135364354_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0135_364_135364354_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_213_137213710_qa_1/environment/Dockerfile b/tasks/0137_213_137213710_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0137_213_137213710_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0137_213_137213710_qa_1/environment/pull_bucket.py b/tasks/0137_213_137213710_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0137_213_137213710_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/0137_213_137213710_qa_1/tests/grader.py b/tasks/0137_213_137213710_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0137_213_137213710_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/0137_213_137213710_qa_1/tests/test.sh b/tasks/0137_213_137213710_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0137_213_137213710_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/0137_398_137398822_qa_3/environment/Dockerfile b/tasks/0137_398_137398822_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0137_398_137398822_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0137_398_137398822_qa_3/environment/pull_bucket.py b/tasks/0137_398_137398822_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0137_398_137398822_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_398_137398822_qa_3/tests/grader.py b/tasks/0137_398_137398822_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0137_398_137398822_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_398_137398822_qa_3/tests/test.sh b/tasks/0137_398_137398822_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0137_398_137398822_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_660_137660235_qa_2/environment/Dockerfile b/tasks/0137_660_137660235_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0137_660_137660235_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0137_660_137660235_qa_2/environment/pull_bucket.py b/tasks/0137_660_137660235_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0137_660_137660235_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/0137_660_137660235_qa_2/tests/grader.py b/tasks/0137_660_137660235_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0137_660_137660235_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/0137_660_137660235_qa_2/tests/test.sh b/tasks/0137_660_137660235_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0137_660_137660235_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_660_137660235_qa_5/environment/Dockerfile b/tasks/0137_660_137660235_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0137_660_137660235_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0137_660_137660235_qa_5/environment/pull_bucket.py b/tasks/0137_660_137660235_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0137_660_137660235_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/0137_660_137660235_qa_5/tests/grader.py b/tasks/0137_660_137660235_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0137_660_137660235_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/0137_660_137660235_qa_5/tests/test.sh b/tasks/0137_660_137660235_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0137_660_137660235_qa_5/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0138_107_138107886_qa_1/environment/Dockerfile b/tasks/0138_107_138107886_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0138_107_138107886_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0138_107_138107886_qa_1/environment/pull_bucket.py b/tasks/0138_107_138107886_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0138_107_138107886_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/0138_107_138107886_qa_1/tests/grader.py b/tasks/0138_107_138107886_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbd769ded89ae8d27c48849ab4c8f6d6135787 --- /dev/null +++ b/tasks/0138_107_138107886_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/0138_107_138107886_qa_1/tests/test.sh b/tasks/0138_107_138107886_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0138_107_138107886_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