AdithyaSK HF Staff commited on
Commit
b26d91d
·
verified ·
1 Parent(s): 36cfdb8

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/0000_886_886039_qa_2/tests/grader.py +68 -117
  2. tasks/0001_181_1181828_qa_4/tests/grader.py +68 -117
  3. tasks/0001_238_1238370_qa_1/tests/grader.py +68 -117
  4. tasks/0001_473_1473187_qa_1/tests/grader.py +68 -153
  5. tasks/0001_521_1521206_qa_2/tests/grader.py +68 -153
  6. tasks/0001_522_1522371_qa_5/tests/grader.py +68 -153
  7. tasks/0001_527_1527039_qa_2/tests/grader.py +68 -117
  8. tasks/0001_541_1541002_qa_2/tests/grader.py +68 -153
  9. tasks/0001_570_1570948_qa_4/tests/grader.py +68 -117
  10. tasks/0001_661_1661005_qa_1/tests/grader.py +68 -117
  11. tasks/0001_666_1666101_qa_5/tests/grader.py +68 -117
  12. tasks/0001_876_1876377_qa_2/tests/grader.py +68 -117
  13. tasks/0001_959_1959663_qa_3/tests/grader.py +68 -153
  14. tasks/0002_094_2094844_qa_1/tests/grader.py +68 -117
  15. tasks/0002_203_2203940_qa_5/environment/Dockerfile +2 -0
  16. tasks/0002_203_2203940_qa_5/environment/pull_bucket.py +41 -0
  17. tasks/0002_203_2203940_qa_5/tests/grader.py +172 -0
  18. tasks/0002_203_2203940_qa_5/tests/test.sh +13 -0
  19. tasks/0002_219_2219893_qa_3/tests/grader.py +68 -117
  20. tasks/0010_909_10909980_qa_3/tests/grader.py +68 -153
  21. tasks/0011_970_11970593_qa_2/tests/grader.py +68 -153
  22. tasks/0013_081_13081725_qa_3/tests/grader.py +68 -117
  23. tasks/0013_604_13604091_qa_2/tests/grader.py +68 -153
  24. tasks/0013_733_13733964_qa_1/tests/grader.py +68 -153
  25. tasks/0013_884_13884693_qa_1/tests/grader.py +68 -117
  26. tasks/0013_911_13911248_qa_1/tests/grader.py +68 -117
  27. tasks/0014_089_14089673_qa_5/tests/grader.py +68 -117
  28. tasks/0014_469_14469283_qa_3/tests/grader.py +68 -153
  29. tasks/0014_469_14469283_qa_4/tests/grader.py +68 -153
  30. tasks/0014_933_14933483_qa_2/tests/grader.py +68 -153
  31. tasks/0015_050_15050710_qa_1/tests/grader.py +68 -117
  32. tasks/0018_456_18456045_qa_5/tests/grader.py +68 -153
  33. tasks/0018_493_18493579_qa_1/tests/grader.py +68 -117
  34. tasks/0020_216_20216126_qa_2/tests/grader.py +68 -117
  35. tasks/0020_613_20613845_qa_4/tests/grader.py +68 -117
  36. tasks/0020_756_20756026_qa_2/tests/grader.py +68 -117
  37. tasks/0021_299_21299002_qa_3/tests/grader.py +68 -153
  38. tasks/0022_193_22193578_qa_5/environment/Dockerfile +2 -0
  39. tasks/0022_193_22193578_qa_5/environment/pull_bucket.py +41 -0
  40. tasks/0022_193_22193578_qa_5/tests/grader.py +172 -0
  41. tasks/0022_193_22193578_qa_5/tests/test.sh +13 -0
  42. tasks/0022_916_22916338_qa_5/tests/grader.py +68 -153
  43. tasks/0023_468_23468316_qa_3/tests/grader.py +68 -117
  44. tasks/0023_583_23583710_qa_4/tests/grader.py +68 -153
  45. tasks/0023_598_23598239_qa_1/tests/grader.py +68 -153
  46. tasks/0023_931_23931431_qa_1/tests/grader.py +68 -117
  47. tasks/0024_069_24069916_qa_1/tests/grader.py +68 -117
  48. tasks/0024_275_24275657_qa_5/environment/Dockerfile +2 -0
  49. tasks/0024_275_24275657_qa_5/environment/pull_bucket.py +41 -0
  50. tasks/0024_275_24275657_qa_5/tests/grader.py +172 -0
tasks/0000_886_886039_qa_2/tests/grader.py CHANGED
@@ -1,42 +1,34 @@
1
- """Deterministic short-answer grader — NO LLM judge.
2
 
3
- Tiers (cheapest -> most expensive), all offline/deterministic:
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
- 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
- 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify)
7
-
8
- CLI form (used by tests/test.sh):
9
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
10
- -> reads predicted answer from stdin
11
- -> writes a single float ('1.0' or '0.0') to stdout
12
  """
13
-
14
  from __future__ import annotations
15
-
16
- import os
17
- import re
18
- import sys
19
  from dataclasses import dataclass
20
 
21
-
22
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
23
 
24
 
25
-
26
  @dataclass
27
  class GradeResult:
28
  reward: float
29
- method: str # "exact" | "numeric" | "llm" | "miss"
30
 
31
 
32
  def _normalize(s: str) -> str:
33
  return re.sub(r"\s+", " ", (s or "").strip().lower())
34
 
35
 
36
- def _to_float(s: str) -> float | None:
37
  if not s:
38
  return None
39
- m = _NUMERIC_RE.search(s.replace(",", ""))
40
  if not m:
41
  return None
42
  try:
@@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None:
45
  return None
46
 
47
 
48
- def _math_verify_match(gold: str, candidate: str) -> bool:
49
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
50
-
51
- Catches equivalences the naive float-parse misses: thousands separators,
52
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
53
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
54
- false positive). No network, no LLM.
55
- """
56
- try:
57
- from math_verify import parse, verify
58
-
59
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
60
- except Exception: # noqa: BLE001
61
- return False
62
 
63
 
64
  def _is_clean_number(s: str) -> bool:
65
- """True iff the whole string IS a single number (allowing a leading/trailing
66
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
67
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
68
- the numeric tier must not fire on it (its `_to_float` would grab the leading
69
- '3' and false-positive-match any answer starting with 3)."""
70
  t = (s or "").strip().strip("%$").strip().replace(",", "")
71
  return bool(_NUMERIC_RE.fullmatch(t))
72
 
73
 
74
- def grade(
75
- gold: str,
76
- candidate: str,
77
- *,
78
- question: str = "",
79
- reward_mode: str = "",
80
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
81
- judge_model: str | None = None, # noqa: ARG001
82
- rel_tol: float = 1e-3,
83
- abs_tol: float = 1e-3,
84
- ) -> GradeResult:
85
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
88
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
89
- """
90
 
 
 
91
  if not gold or candidate is None:
92
  return GradeResult(0.0, "miss")
93
 
94
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
95
  if _normalize(gold) == _normalize(candidate):
96
  return GradeResult(1.0, "exact")
97
 
98
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
99
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
100
- # the leading number; those must go to exact/math_verify, which fail closed).
101
- if reward_mode == "numeric" or _is_clean_number(gold):
102
  g, c = _to_float(gold), _to_float(candidate)
103
  if g is not None and c is not None:
104
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
105
  return GradeResult(1.0, "numeric")
 
 
 
 
106
 
107
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
108
  if _math_verify_match(gold, candidate):
109
  return GradeResult(1.0, "math_verify")
110
 
111
  return GradeResult(0.0, "miss")
112
 
113
 
114
- def _tool_calls() -> int | None:
115
- """Number of agent tool calls this rollout, for the efficiency reward.
116
-
117
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
118
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
119
- (efficiency reward becomes null — the harness didn't report a count).
120
- """
121
  try:
122
  with open("/workdir/.n_tool_calls") as fh:
123
  return int(fh.read().strip())
@@ -132,24 +121,17 @@ def _tool_calls() -> int | None:
132
  return None
133
 
134
 
135
- def _tool_efficiency(n_calls: int | None) -> float | None:
136
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
137
-
138
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
139
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
140
- RL reward combiner decides gating/weights.
141
- """
142
- if n_calls is None:
143
  return None
144
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
145
  if budget <= 0:
146
  return None
147
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
148
 
149
 
150
- def _tols() -> tuple[float, float]:
151
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
152
- def _f(name: str) -> float:
153
  try:
154
  return float(os.environ.get(name, "") or 1e-3)
155
  except ValueError:
@@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]:
158
 
159
 
160
  def main_cli() -> int:
161
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
162
-
163
- Inputs (via env vars set by Harbor's [verifier.env]):
164
- EXPECTED_ANSWER — the gold
165
- QUESTION — the original question
166
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
167
-
168
- Predicted answer is read from stdin.
169
- Single float written to stdout. Exit code is always 0.
170
- """
171
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
172
  question = (os.environ.get("QUESTION") or "").strip()
173
  candidate = sys.stdin.read().strip()
174
  at, rt = _tols()
175
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
176
- print(f"{result.reward:.1f}")
177
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
178
- file=sys.stderr)
179
  return 0
180
 
181
 
182
  def main_json() -> int:
183
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
184
-
185
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
186
- correctness — 1.0 iff graded answer matches gold, else 0.0
187
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
188
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
189
-
190
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
191
- """
192
  import json
193
-
194
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
195
  question = (os.environ.get("QUESTION") or "").strip()
196
  candidate = sys.stdin.read().strip()
197
-
198
  if not candidate:
199
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
200
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
201
  return 0
202
-
203
  at, rt = _tols()
204
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
205
- n_calls = _tool_calls()
206
- eff = _tool_efficiency(n_calls)
207
- print(json.dumps({
208
- "correctness": float(result.reward),
209
- "submission": 1.0,
210
- "tool_efficiency": eff,
211
- }))
212
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
213
- f"correctness={result.reward} method={result.method} "
214
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
215
  return 0
216
 
217
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
17
 
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0001_181_1181828_qa_4/tests/grader.py CHANGED
@@ -1,42 +1,34 @@
1
- """Deterministic short-answer grader — NO LLM judge.
2
 
3
- Tiers (cheapest -> most expensive), all offline/deterministic:
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
- 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
- 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify)
7
-
8
- CLI form (used by tests/test.sh):
9
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
10
- -> reads predicted answer from stdin
11
- -> writes a single float ('1.0' or '0.0') to stdout
12
  """
13
-
14
  from __future__ import annotations
15
-
16
- import os
17
- import re
18
- import sys
19
  from dataclasses import dataclass
20
 
21
-
22
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
23
 
24
 
25
-
26
  @dataclass
27
  class GradeResult:
28
  reward: float
29
- method: str # "exact" | "numeric" | "llm" | "miss"
30
 
31
 
32
  def _normalize(s: str) -> str:
33
  return re.sub(r"\s+", " ", (s or "").strip().lower())
34
 
35
 
36
- def _to_float(s: str) -> float | None:
37
  if not s:
38
  return None
39
- m = _NUMERIC_RE.search(s.replace(",", ""))
40
  if not m:
41
  return None
42
  try:
@@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None:
45
  return None
46
 
47
 
48
- def _math_verify_match(gold: str, candidate: str) -> bool:
49
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
50
-
51
- Catches equivalences the naive float-parse misses: thousands separators,
52
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
53
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
54
- false positive). No network, no LLM.
55
- """
56
- try:
57
- from math_verify import parse, verify
58
-
59
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
60
- except Exception: # noqa: BLE001
61
- return False
62
 
63
 
64
  def _is_clean_number(s: str) -> bool:
65
- """True iff the whole string IS a single number (allowing a leading/trailing
66
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
67
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
68
- the numeric tier must not fire on it (its `_to_float` would grab the leading
69
- '3' and false-positive-match any answer starting with 3)."""
70
  t = (s or "").strip().strip("%$").strip().replace(",", "")
71
  return bool(_NUMERIC_RE.fullmatch(t))
72
 
73
 
74
- def grade(
75
- gold: str,
76
- candidate: str,
77
- *,
78
- question: str = "",
79
- reward_mode: str = "",
80
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
81
- judge_model: str | None = None, # noqa: ARG001
82
- rel_tol: float = 1e-3,
83
- abs_tol: float = 1e-3,
84
- ) -> GradeResult:
85
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
88
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
89
- """
90
 
 
 
91
  if not gold or candidate is None:
92
  return GradeResult(0.0, "miss")
93
 
94
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
95
  if _normalize(gold) == _normalize(candidate):
96
  return GradeResult(1.0, "exact")
97
 
98
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
99
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
100
- # the leading number; those must go to exact/math_verify, which fail closed).
101
- if reward_mode == "numeric" or _is_clean_number(gold):
102
  g, c = _to_float(gold), _to_float(candidate)
103
  if g is not None and c is not None:
104
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
105
  return GradeResult(1.0, "numeric")
 
 
 
 
106
 
107
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
108
  if _math_verify_match(gold, candidate):
109
  return GradeResult(1.0, "math_verify")
110
 
111
  return GradeResult(0.0, "miss")
112
 
113
 
114
- def _tool_calls() -> int | None:
115
- """Number of agent tool calls this rollout, for the efficiency reward.
116
-
117
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
118
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
119
- (efficiency reward becomes null — the harness didn't report a count).
120
- """
121
  try:
122
  with open("/workdir/.n_tool_calls") as fh:
123
  return int(fh.read().strip())
@@ -132,24 +121,17 @@ def _tool_calls() -> int | None:
132
  return None
133
 
134
 
135
- def _tool_efficiency(n_calls: int | None) -> float | None:
136
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
137
-
138
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
139
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
140
- RL reward combiner decides gating/weights.
141
- """
142
- if n_calls is None:
143
  return None
144
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
145
  if budget <= 0:
146
  return None
147
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
148
 
149
 
150
- def _tols() -> tuple[float, float]:
151
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
152
- def _f(name: str) -> float:
153
  try:
154
  return float(os.environ.get(name, "") or 1e-3)
155
  except ValueError:
@@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]:
158
 
159
 
160
  def main_cli() -> int:
161
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
162
-
163
- Inputs (via env vars set by Harbor's [verifier.env]):
164
- EXPECTED_ANSWER — the gold
165
- QUESTION — the original question
166
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
167
-
168
- Predicted answer is read from stdin.
169
- Single float written to stdout. Exit code is always 0.
170
- """
171
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
172
  question = (os.environ.get("QUESTION") or "").strip()
173
  candidate = sys.stdin.read().strip()
174
  at, rt = _tols()
175
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
176
- print(f"{result.reward:.1f}")
177
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
178
- file=sys.stderr)
179
  return 0
180
 
181
 
182
  def main_json() -> int:
183
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
184
-
185
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
186
- correctness — 1.0 iff graded answer matches gold, else 0.0
187
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
188
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
189
-
190
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
191
- """
192
  import json
193
-
194
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
195
  question = (os.environ.get("QUESTION") or "").strip()
196
  candidate = sys.stdin.read().strip()
197
-
198
  if not candidate:
199
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
200
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
201
  return 0
202
-
203
  at, rt = _tols()
204
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
205
- n_calls = _tool_calls()
206
- eff = _tool_efficiency(n_calls)
207
- print(json.dumps({
208
- "correctness": float(result.reward),
209
- "submission": 1.0,
210
- "tool_efficiency": eff,
211
- }))
212
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
213
- f"correctness={result.reward} method={result.method} "
214
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
215
  return 0
216
 
217
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
17
 
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0001_238_1238370_qa_1/tests/grader.py CHANGED
@@ -1,42 +1,34 @@
1
- """Deterministic short-answer grader — NO LLM judge.
2
 
3
- Tiers (cheapest -> most expensive), all offline/deterministic:
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
- 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
- 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify)
7
-
8
- CLI form (used by tests/test.sh):
9
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
10
- -> reads predicted answer from stdin
11
- -> writes a single float ('1.0' or '0.0') to stdout
12
  """
13
-
14
  from __future__ import annotations
15
-
16
- import os
17
- import re
18
- import sys
19
  from dataclasses import dataclass
20
 
21
-
22
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
23
 
24
 
25
-
26
  @dataclass
27
  class GradeResult:
28
  reward: float
29
- method: str # "exact" | "numeric" | "llm" | "miss"
30
 
31
 
32
  def _normalize(s: str) -> str:
33
  return re.sub(r"\s+", " ", (s or "").strip().lower())
34
 
35
 
36
- def _to_float(s: str) -> float | None:
37
  if not s:
38
  return None
39
- m = _NUMERIC_RE.search(s.replace(",", ""))
40
  if not m:
41
  return None
42
  try:
@@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None:
45
  return None
46
 
47
 
48
- def _math_verify_match(gold: str, candidate: str) -> bool:
49
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
50
-
51
- Catches equivalences the naive float-parse misses: thousands separators,
52
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
53
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
54
- false positive). No network, no LLM.
55
- """
56
- try:
57
- from math_verify import parse, verify
58
-
59
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
60
- except Exception: # noqa: BLE001
61
- return False
62
 
63
 
64
  def _is_clean_number(s: str) -> bool:
65
- """True iff the whole string IS a single number (allowing a leading/trailing
66
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
67
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
68
- the numeric tier must not fire on it (its `_to_float` would grab the leading
69
- '3' and false-positive-match any answer starting with 3)."""
70
  t = (s or "").strip().strip("%$").strip().replace(",", "")
71
  return bool(_NUMERIC_RE.fullmatch(t))
72
 
73
 
74
- def grade(
75
- gold: str,
76
- candidate: str,
77
- *,
78
- question: str = "",
79
- reward_mode: str = "",
80
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
81
- judge_model: str | None = None, # noqa: ARG001
82
- rel_tol: float = 1e-3,
83
- abs_tol: float = 1e-3,
84
- ) -> GradeResult:
85
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
88
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
89
- """
90
 
 
 
91
  if not gold or candidate is None:
92
  return GradeResult(0.0, "miss")
93
 
94
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
95
  if _normalize(gold) == _normalize(candidate):
96
  return GradeResult(1.0, "exact")
97
 
98
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
99
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
100
- # the leading number; those must go to exact/math_verify, which fail closed).
101
- if reward_mode == "numeric" or _is_clean_number(gold):
102
  g, c = _to_float(gold), _to_float(candidate)
103
  if g is not None and c is not None:
104
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
105
  return GradeResult(1.0, "numeric")
 
 
 
 
106
 
107
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
108
  if _math_verify_match(gold, candidate):
109
  return GradeResult(1.0, "math_verify")
110
 
111
  return GradeResult(0.0, "miss")
112
 
113
 
114
- def _tool_calls() -> int | None:
115
- """Number of agent tool calls this rollout, for the efficiency reward.
116
-
117
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
118
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
119
- (efficiency reward becomes null — the harness didn't report a count).
120
- """
121
  try:
122
  with open("/workdir/.n_tool_calls") as fh:
123
  return int(fh.read().strip())
@@ -132,24 +121,17 @@ def _tool_calls() -> int | None:
132
  return None
133
 
134
 
135
- def _tool_efficiency(n_calls: int | None) -> float | None:
136
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
137
-
138
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
139
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
140
- RL reward combiner decides gating/weights.
141
- """
142
- if n_calls is None:
143
  return None
144
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
145
  if budget <= 0:
146
  return None
147
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
148
 
149
 
150
- def _tols() -> tuple[float, float]:
151
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
152
- def _f(name: str) -> float:
153
  try:
154
  return float(os.environ.get(name, "") or 1e-3)
155
  except ValueError:
@@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]:
158
 
159
 
160
  def main_cli() -> int:
161
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
162
-
163
- Inputs (via env vars set by Harbor's [verifier.env]):
164
- EXPECTED_ANSWER — the gold
165
- QUESTION — the original question
166
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
167
-
168
- Predicted answer is read from stdin.
169
- Single float written to stdout. Exit code is always 0.
170
- """
171
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
172
  question = (os.environ.get("QUESTION") or "").strip()
173
  candidate = sys.stdin.read().strip()
174
  at, rt = _tols()
175
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
176
- print(f"{result.reward:.1f}")
177
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
178
- file=sys.stderr)
179
  return 0
180
 
181
 
182
  def main_json() -> int:
183
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
184
-
185
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
186
- correctness — 1.0 iff graded answer matches gold, else 0.0
187
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
188
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
189
-
190
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
191
- """
192
  import json
193
-
194
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
195
  question = (os.environ.get("QUESTION") or "").strip()
196
  candidate = sys.stdin.read().strip()
197
-
198
  if not candidate:
199
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
200
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
201
  return 0
202
-
203
  at, rt = _tols()
204
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
205
- n_calls = _tool_calls()
206
- eff = _tool_efficiency(n_calls)
207
- print(json.dumps({
208
- "correctness": float(result.reward),
209
- "submission": 1.0,
210
- "tool_efficiency": eff,
211
- }))
212
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
213
- f"correctness={result.reward} method={result.method} "
214
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
215
  return 0
216
 
217
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
17
 
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0001_473_1473187_qa_1/tests/grader.py CHANGED
@@ -1,78 +1,34 @@
1
- """Shared three-tier grader.
2
 
3
- Used by both runtimes:
4
- * `env/server.py` — inline inside the `final_answer` ORS @tool method
5
- * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py
6
- and invoked with `python3 /tests/grader.py < /workdir/answer.txt`
7
-
8
- Tiers (cheapest → most expensive):
9
  1. Exact (case-insensitive, whitespace-collapsed)
10
- 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3)
11
- 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt)
12
- — only invoked if OPENAI_API_KEY is set
13
-
14
- CLI form (used by tests/test.sh):
15
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
16
- → reads predicted answer from stdin
17
- → writes a single float ('1.0' or '0.0') to stdout
18
- → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt
19
  """
20
-
21
  from __future__ import annotations
22
-
23
- import os
24
- import re
25
- import sys
26
  from dataclasses import dataclass
27
 
28
-
29
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
30
 
31
- # Locked in PLAN.md §"Locked decisions" — adapted from
32
- # https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py
33
- JUDGE_PROMPT = """You are grading short answers from a data-science agent.
34
- Decide whether the predicted answer is semantically equivalent to the gold answer.
35
-
36
- Rules:
37
- - Case, punctuation, whitespace, articles ("the"), and trailing units don't matter.
38
- - For numbers: predicted must match to the last significant figure of the gold
39
- (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT).
40
- - Extra surrounding prose is fine if the gold value is clearly stated
41
- (gold "5", predicted "There are 5 distinct categories" -> CORRECT).
42
- - Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT).
43
- - Parenthetical annotations in the gold are equivalence hints, not required
44
- (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT;
45
- gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT).
46
- - Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X%
47
- is CORRECT as long as the core numeric value matches
48
- (gold "21.334% in 2014", predicted "21.334" -> CORRECT;
49
- gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch).
50
- - Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one
51
- thing (e.g. "which model?"), predicting either listed value is CORRECT.
52
- - If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED.
53
- - If it commits to a different value -> INCORRECT.
54
-
55
- Question: {question}
56
- Gold answer: {gold}
57
- Predicted answer: {pred}
58
-
59
- Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED)."""
60
-
61
 
62
  @dataclass
63
  class GradeResult:
64
  reward: float
65
- method: str # "exact" | "numeric" | "llm" | "miss"
66
 
67
 
68
  def _normalize(s: str) -> str:
69
  return re.sub(r"\s+", " ", (s or "").strip().lower())
70
 
71
 
72
- def _to_float(s: str) -> float | None:
73
  if not s:
74
  return None
75
- m = _NUMERIC_RE.search(s.replace(",", ""))
76
  if not m:
77
  return None
78
  try:
@@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None:
81
  return None
82
 
83
 
84
- def _math_verify_match(gold: str, candidate: str) -> bool:
85
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
86
-
87
- Catches equivalences the naive float-parse misses: thousands separators,
88
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
89
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
90
- false positive). No network, no LLM.
91
- """
92
- try:
93
- from math_verify import parse, verify
94
-
95
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
96
- except Exception: # noqa: BLE001
97
- return False
98
 
99
 
100
  def _is_clean_number(s: str) -> bool:
101
- """True iff the whole string IS a single number (allowing a leading/trailing
102
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
103
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
104
- the numeric tier must not fire on it (its `_to_float` would grab the leading
105
- '3' and false-positive-match any answer starting with 3)."""
106
  t = (s or "").strip().strip("%$").strip().replace(",", "")
107
  return bool(_NUMERIC_RE.fullmatch(t))
108
 
109
 
110
- def grade(
111
- gold: str,
112
- candidate: str,
113
- *,
114
- question: str = "",
115
- reward_mode: str = "",
116
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
117
- judge_model: str | None = None, # noqa: ARG001
118
- rel_tol: float = 1e-3,
119
- abs_tol: float = 1e-3,
120
- ) -> GradeResult:
121
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
124
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
125
- """
126
 
 
 
127
  if not gold or candidate is None:
128
  return GradeResult(0.0, "miss")
129
 
130
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
131
  if _normalize(gold) == _normalize(candidate):
132
  return GradeResult(1.0, "exact")
133
 
134
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
135
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
136
- # the leading number; those must go to exact/math_verify, which fail closed).
137
- if reward_mode == "numeric" or _is_clean_number(gold):
138
  g, c = _to_float(gold), _to_float(candidate)
139
  if g is not None and c is not None:
140
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
141
  return GradeResult(1.0, "numeric")
 
 
 
 
142
 
143
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
144
  if _math_verify_match(gold, candidate):
145
  return GradeResult(1.0, "math_verify")
146
 
147
  return GradeResult(0.0, "miss")
148
 
149
 
150
- def _tool_calls() -> int | None:
151
- """Number of agent tool calls this rollout, for the efficiency reward.
152
-
153
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
154
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
155
- (efficiency reward becomes null — the harness didn't report a count).
156
- """
157
  try:
158
  with open("/workdir/.n_tool_calls") as fh:
159
  return int(fh.read().strip())
@@ -168,24 +121,17 @@ def _tool_calls() -> int | None:
168
  return None
169
 
170
 
171
- def _tool_efficiency(n_calls: int | None) -> float | None:
172
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
173
-
174
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
175
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
176
- RL reward combiner decides gating/weights.
177
- """
178
- if n_calls is None:
179
  return None
180
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
181
  if budget <= 0:
182
  return None
183
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
184
 
185
 
186
- def _tols() -> tuple[float, float]:
187
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
188
- def _f(name: str) -> float:
189
  try:
190
  return float(os.environ.get(name, "") or 1e-3)
191
  except ValueError:
@@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]:
194
 
195
 
196
  def main_cli() -> int:
197
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
198
-
199
- Inputs (via env vars set by Harbor's [verifier.env]):
200
- EXPECTED_ANSWER — the gold
201
- QUESTION — the original question
202
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
203
-
204
- Predicted answer is read from stdin.
205
- Single float written to stdout. Exit code is always 0.
206
- """
207
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
208
  question = (os.environ.get("QUESTION") or "").strip()
209
  candidate = sys.stdin.read().strip()
210
  at, rt = _tols()
211
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
212
- print(f"{result.reward:.1f}")
213
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
214
- file=sys.stderr)
215
  return 0
216
 
217
 
218
  def main_json() -> int:
219
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
220
-
221
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
222
- correctness — 1.0 iff graded answer matches gold, else 0.0
223
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
224
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
225
-
226
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
227
- """
228
  import json
229
-
230
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
231
  question = (os.environ.get("QUESTION") or "").strip()
232
  candidate = sys.stdin.read().strip()
233
-
234
  if not candidate:
235
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
236
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
237
  return 0
238
-
239
  at, rt = _tols()
240
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
241
- n_calls = _tool_calls()
242
- eff = _tool_efficiency(n_calls)
243
- print(json.dumps({
244
- "correctness": float(result.reward),
245
- "submission": 1.0,
246
- "tool_efficiency": eff,
247
- }))
248
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
249
- f"correctness={result.reward} method={result.method} "
250
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
251
  return 0
252
 
253
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
 
 
 
 
 
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0001_521_1521206_qa_2/tests/grader.py CHANGED
@@ -1,78 +1,34 @@
1
- """Shared three-tier grader.
2
 
3
- Used by both runtimes:
4
- * `env/server.py` — inline inside the `final_answer` ORS @tool method
5
- * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py
6
- and invoked with `python3 /tests/grader.py < /workdir/answer.txt`
7
-
8
- Tiers (cheapest → most expensive):
9
  1. Exact (case-insensitive, whitespace-collapsed)
10
- 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3)
11
- 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt)
12
- — only invoked if OPENAI_API_KEY is set
13
-
14
- CLI form (used by tests/test.sh):
15
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
16
- → reads predicted answer from stdin
17
- → writes a single float ('1.0' or '0.0') to stdout
18
- → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt
19
  """
20
-
21
  from __future__ import annotations
22
-
23
- import os
24
- import re
25
- import sys
26
  from dataclasses import dataclass
27
 
28
-
29
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
30
 
31
- # Locked in PLAN.md §"Locked decisions" — adapted from
32
- # https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py
33
- JUDGE_PROMPT = """You are grading short answers from a data-science agent.
34
- Decide whether the predicted answer is semantically equivalent to the gold answer.
35
-
36
- Rules:
37
- - Case, punctuation, whitespace, articles ("the"), and trailing units don't matter.
38
- - For numbers: predicted must match to the last significant figure of the gold
39
- (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT).
40
- - Extra surrounding prose is fine if the gold value is clearly stated
41
- (gold "5", predicted "There are 5 distinct categories" -> CORRECT).
42
- - Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT).
43
- - Parenthetical annotations in the gold are equivalence hints, not required
44
- (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT;
45
- gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT).
46
- - Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X%
47
- is CORRECT as long as the core numeric value matches
48
- (gold "21.334% in 2014", predicted "21.334" -> CORRECT;
49
- gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch).
50
- - Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one
51
- thing (e.g. "which model?"), predicting either listed value is CORRECT.
52
- - If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED.
53
- - If it commits to a different value -> INCORRECT.
54
-
55
- Question: {question}
56
- Gold answer: {gold}
57
- Predicted answer: {pred}
58
-
59
- Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED)."""
60
-
61
 
62
  @dataclass
63
  class GradeResult:
64
  reward: float
65
- method: str # "exact" | "numeric" | "llm" | "miss"
66
 
67
 
68
  def _normalize(s: str) -> str:
69
  return re.sub(r"\s+", " ", (s or "").strip().lower())
70
 
71
 
72
- def _to_float(s: str) -> float | None:
73
  if not s:
74
  return None
75
- m = _NUMERIC_RE.search(s.replace(",", ""))
76
  if not m:
77
  return None
78
  try:
@@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None:
81
  return None
82
 
83
 
84
- def _math_verify_match(gold: str, candidate: str) -> bool:
85
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
86
-
87
- Catches equivalences the naive float-parse misses: thousands separators,
88
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
89
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
90
- false positive). No network, no LLM.
91
- """
92
- try:
93
- from math_verify import parse, verify
94
-
95
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
96
- except Exception: # noqa: BLE001
97
- return False
98
 
99
 
100
  def _is_clean_number(s: str) -> bool:
101
- """True iff the whole string IS a single number (allowing a leading/trailing
102
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
103
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
104
- the numeric tier must not fire on it (its `_to_float` would grab the leading
105
- '3' and false-positive-match any answer starting with 3)."""
106
  t = (s or "").strip().strip("%$").strip().replace(",", "")
107
  return bool(_NUMERIC_RE.fullmatch(t))
108
 
109
 
110
- def grade(
111
- gold: str,
112
- candidate: str,
113
- *,
114
- question: str = "",
115
- reward_mode: str = "",
116
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
117
- judge_model: str | None = None, # noqa: ARG001
118
- rel_tol: float = 1e-3,
119
- abs_tol: float = 1e-3,
120
- ) -> GradeResult:
121
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
124
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
125
- """
126
 
 
 
127
  if not gold or candidate is None:
128
  return GradeResult(0.0, "miss")
129
 
130
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
131
  if _normalize(gold) == _normalize(candidate):
132
  return GradeResult(1.0, "exact")
133
 
134
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
135
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
136
- # the leading number; those must go to exact/math_verify, which fail closed).
137
- if reward_mode == "numeric" or _is_clean_number(gold):
138
  g, c = _to_float(gold), _to_float(candidate)
139
  if g is not None and c is not None:
140
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
141
  return GradeResult(1.0, "numeric")
 
 
 
 
142
 
143
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
144
  if _math_verify_match(gold, candidate):
145
  return GradeResult(1.0, "math_verify")
146
 
147
  return GradeResult(0.0, "miss")
148
 
149
 
150
- def _tool_calls() -> int | None:
151
- """Number of agent tool calls this rollout, for the efficiency reward.
152
-
153
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
154
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
155
- (efficiency reward becomes null — the harness didn't report a count).
156
- """
157
  try:
158
  with open("/workdir/.n_tool_calls") as fh:
159
  return int(fh.read().strip())
@@ -168,24 +121,17 @@ def _tool_calls() -> int | None:
168
  return None
169
 
170
 
171
- def _tool_efficiency(n_calls: int | None) -> float | None:
172
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
173
-
174
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
175
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
176
- RL reward combiner decides gating/weights.
177
- """
178
- if n_calls is None:
179
  return None
180
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
181
  if budget <= 0:
182
  return None
183
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
184
 
185
 
186
- def _tols() -> tuple[float, float]:
187
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
188
- def _f(name: str) -> float:
189
  try:
190
  return float(os.environ.get(name, "") or 1e-3)
191
  except ValueError:
@@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]:
194
 
195
 
196
  def main_cli() -> int:
197
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
198
-
199
- Inputs (via env vars set by Harbor's [verifier.env]):
200
- EXPECTED_ANSWER — the gold
201
- QUESTION — the original question
202
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
203
-
204
- Predicted answer is read from stdin.
205
- Single float written to stdout. Exit code is always 0.
206
- """
207
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
208
  question = (os.environ.get("QUESTION") or "").strip()
209
  candidate = sys.stdin.read().strip()
210
  at, rt = _tols()
211
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
212
- print(f"{result.reward:.1f}")
213
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
214
- file=sys.stderr)
215
  return 0
216
 
217
 
218
  def main_json() -> int:
219
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
220
-
221
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
222
- correctness — 1.0 iff graded answer matches gold, else 0.0
223
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
224
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
225
-
226
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
227
- """
228
  import json
229
-
230
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
231
  question = (os.environ.get("QUESTION") or "").strip()
232
  candidate = sys.stdin.read().strip()
233
-
234
  if not candidate:
235
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
236
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
237
  return 0
238
-
239
  at, rt = _tols()
240
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
241
- n_calls = _tool_calls()
242
- eff = _tool_efficiency(n_calls)
243
- print(json.dumps({
244
- "correctness": float(result.reward),
245
- "submission": 1.0,
246
- "tool_efficiency": eff,
247
- }))
248
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
249
- f"correctness={result.reward} method={result.method} "
250
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
251
  return 0
252
 
253
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
 
 
 
 
 
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0001_522_1522371_qa_5/tests/grader.py CHANGED
@@ -1,78 +1,34 @@
1
- """Shared three-tier grader.
2
 
3
- Used by both runtimes:
4
- * `env/server.py` — inline inside the `final_answer` ORS @tool method
5
- * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py
6
- and invoked with `python3 /tests/grader.py < /workdir/answer.txt`
7
-
8
- Tiers (cheapest → most expensive):
9
  1. Exact (case-insensitive, whitespace-collapsed)
10
- 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3)
11
- 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt)
12
- — only invoked if OPENAI_API_KEY is set
13
-
14
- CLI form (used by tests/test.sh):
15
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
16
- → reads predicted answer from stdin
17
- → writes a single float ('1.0' or '0.0') to stdout
18
- → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt
19
  """
20
-
21
  from __future__ import annotations
22
-
23
- import os
24
- import re
25
- import sys
26
  from dataclasses import dataclass
27
 
28
-
29
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
30
 
31
- # Locked in PLAN.md §"Locked decisions" — adapted from
32
- # https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py
33
- JUDGE_PROMPT = """You are grading short answers from a data-science agent.
34
- Decide whether the predicted answer is semantically equivalent to the gold answer.
35
-
36
- Rules:
37
- - Case, punctuation, whitespace, articles ("the"), and trailing units don't matter.
38
- - For numbers: predicted must match to the last significant figure of the gold
39
- (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT).
40
- - Extra surrounding prose is fine if the gold value is clearly stated
41
- (gold "5", predicted "There are 5 distinct categories" -> CORRECT).
42
- - Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT).
43
- - Parenthetical annotations in the gold are equivalence hints, not required
44
- (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT;
45
- gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT).
46
- - Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X%
47
- is CORRECT as long as the core numeric value matches
48
- (gold "21.334% in 2014", predicted "21.334" -> CORRECT;
49
- gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch).
50
- - Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one
51
- thing (e.g. "which model?"), predicting either listed value is CORRECT.
52
- - If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED.
53
- - If it commits to a different value -> INCORRECT.
54
-
55
- Question: {question}
56
- Gold answer: {gold}
57
- Predicted answer: {pred}
58
-
59
- Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED)."""
60
-
61
 
62
  @dataclass
63
  class GradeResult:
64
  reward: float
65
- method: str # "exact" | "numeric" | "llm" | "miss"
66
 
67
 
68
  def _normalize(s: str) -> str:
69
  return re.sub(r"\s+", " ", (s or "").strip().lower())
70
 
71
 
72
- def _to_float(s: str) -> float | None:
73
  if not s:
74
  return None
75
- m = _NUMERIC_RE.search(s.replace(",", ""))
76
  if not m:
77
  return None
78
  try:
@@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None:
81
  return None
82
 
83
 
84
- def _math_verify_match(gold: str, candidate: str) -> bool:
85
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
86
-
87
- Catches equivalences the naive float-parse misses: thousands separators,
88
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
89
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
90
- false positive). No network, no LLM.
91
- """
92
- try:
93
- from math_verify import parse, verify
94
-
95
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
96
- except Exception: # noqa: BLE001
97
- return False
98
 
99
 
100
  def _is_clean_number(s: str) -> bool:
101
- """True iff the whole string IS a single number (allowing a leading/trailing
102
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
103
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
104
- the numeric tier must not fire on it (its `_to_float` would grab the leading
105
- '3' and false-positive-match any answer starting with 3)."""
106
  t = (s or "").strip().strip("%$").strip().replace(",", "")
107
  return bool(_NUMERIC_RE.fullmatch(t))
108
 
109
 
110
- def grade(
111
- gold: str,
112
- candidate: str,
113
- *,
114
- question: str = "",
115
- reward_mode: str = "",
116
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
117
- judge_model: str | None = None, # noqa: ARG001
118
- rel_tol: float = 1e-3,
119
- abs_tol: float = 1e-3,
120
- ) -> GradeResult:
121
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
124
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
125
- """
126
 
 
 
127
  if not gold or candidate is None:
128
  return GradeResult(0.0, "miss")
129
 
130
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
131
  if _normalize(gold) == _normalize(candidate):
132
  return GradeResult(1.0, "exact")
133
 
134
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
135
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
136
- # the leading number; those must go to exact/math_verify, which fail closed).
137
- if reward_mode == "numeric" or _is_clean_number(gold):
138
  g, c = _to_float(gold), _to_float(candidate)
139
  if g is not None and c is not None:
140
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
141
  return GradeResult(1.0, "numeric")
 
 
 
 
142
 
143
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
144
  if _math_verify_match(gold, candidate):
145
  return GradeResult(1.0, "math_verify")
146
 
147
  return GradeResult(0.0, "miss")
148
 
149
 
150
- def _tool_calls() -> int | None:
151
- """Number of agent tool calls this rollout, for the efficiency reward.
152
-
153
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
154
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
155
- (efficiency reward becomes null — the harness didn't report a count).
156
- """
157
  try:
158
  with open("/workdir/.n_tool_calls") as fh:
159
  return int(fh.read().strip())
@@ -168,24 +121,17 @@ def _tool_calls() -> int | None:
168
  return None
169
 
170
 
171
- def _tool_efficiency(n_calls: int | None) -> float | None:
172
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
173
-
174
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
175
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
176
- RL reward combiner decides gating/weights.
177
- """
178
- if n_calls is None:
179
  return None
180
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
181
  if budget <= 0:
182
  return None
183
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
184
 
185
 
186
- def _tols() -> tuple[float, float]:
187
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
188
- def _f(name: str) -> float:
189
  try:
190
  return float(os.environ.get(name, "") or 1e-3)
191
  except ValueError:
@@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]:
194
 
195
 
196
  def main_cli() -> int:
197
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
198
-
199
- Inputs (via env vars set by Harbor's [verifier.env]):
200
- EXPECTED_ANSWER — the gold
201
- QUESTION — the original question
202
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
203
-
204
- Predicted answer is read from stdin.
205
- Single float written to stdout. Exit code is always 0.
206
- """
207
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
208
  question = (os.environ.get("QUESTION") or "").strip()
209
  candidate = sys.stdin.read().strip()
210
  at, rt = _tols()
211
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
212
- print(f"{result.reward:.1f}")
213
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
214
- file=sys.stderr)
215
  return 0
216
 
217
 
218
  def main_json() -> int:
219
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
220
-
221
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
222
- correctness — 1.0 iff graded answer matches gold, else 0.0
223
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
224
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
225
-
226
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
227
- """
228
  import json
229
-
230
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
231
  question = (os.environ.get("QUESTION") or "").strip()
232
  candidate = sys.stdin.read().strip()
233
-
234
  if not candidate:
235
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
236
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
237
  return 0
238
-
239
  at, rt = _tols()
240
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
241
- n_calls = _tool_calls()
242
- eff = _tool_efficiency(n_calls)
243
- print(json.dumps({
244
- "correctness": float(result.reward),
245
- "submission": 1.0,
246
- "tool_efficiency": eff,
247
- }))
248
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
249
- f"correctness={result.reward} method={result.method} "
250
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
251
  return 0
252
 
253
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
 
 
 
 
 
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0001_527_1527039_qa_2/tests/grader.py CHANGED
@@ -1,42 +1,34 @@
1
- """Deterministic short-answer grader — NO LLM judge.
2
 
3
- Tiers (cheapest -> most expensive), all offline/deterministic:
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
- 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
- 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify)
7
-
8
- CLI form (used by tests/test.sh):
9
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
10
- -> reads predicted answer from stdin
11
- -> writes a single float ('1.0' or '0.0') to stdout
12
  """
13
-
14
  from __future__ import annotations
15
-
16
- import os
17
- import re
18
- import sys
19
  from dataclasses import dataclass
20
 
21
-
22
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
23
 
24
 
25
-
26
  @dataclass
27
  class GradeResult:
28
  reward: float
29
- method: str # "exact" | "numeric" | "llm" | "miss"
30
 
31
 
32
  def _normalize(s: str) -> str:
33
  return re.sub(r"\s+", " ", (s or "").strip().lower())
34
 
35
 
36
- def _to_float(s: str) -> float | None:
37
  if not s:
38
  return None
39
- m = _NUMERIC_RE.search(s.replace(",", ""))
40
  if not m:
41
  return None
42
  try:
@@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None:
45
  return None
46
 
47
 
48
- def _math_verify_match(gold: str, candidate: str) -> bool:
49
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
50
-
51
- Catches equivalences the naive float-parse misses: thousands separators,
52
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
53
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
54
- false positive). No network, no LLM.
55
- """
56
- try:
57
- from math_verify import parse, verify
58
-
59
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
60
- except Exception: # noqa: BLE001
61
- return False
62
 
63
 
64
  def _is_clean_number(s: str) -> bool:
65
- """True iff the whole string IS a single number (allowing a leading/trailing
66
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
67
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
68
- the numeric tier must not fire on it (its `_to_float` would grab the leading
69
- '3' and false-positive-match any answer starting with 3)."""
70
  t = (s or "").strip().strip("%$").strip().replace(",", "")
71
  return bool(_NUMERIC_RE.fullmatch(t))
72
 
73
 
74
- def grade(
75
- gold: str,
76
- candidate: str,
77
- *,
78
- question: str = "",
79
- reward_mode: str = "",
80
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
81
- judge_model: str | None = None, # noqa: ARG001
82
- rel_tol: float = 1e-3,
83
- abs_tol: float = 1e-3,
84
- ) -> GradeResult:
85
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
88
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
89
- """
90
 
 
 
91
  if not gold or candidate is None:
92
  return GradeResult(0.0, "miss")
93
 
94
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
95
  if _normalize(gold) == _normalize(candidate):
96
  return GradeResult(1.0, "exact")
97
 
98
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
99
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
100
- # the leading number; those must go to exact/math_verify, which fail closed).
101
- if reward_mode == "numeric" or _is_clean_number(gold):
102
  g, c = _to_float(gold), _to_float(candidate)
103
  if g is not None and c is not None:
104
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
105
  return GradeResult(1.0, "numeric")
 
 
 
 
106
 
107
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
108
  if _math_verify_match(gold, candidate):
109
  return GradeResult(1.0, "math_verify")
110
 
111
  return GradeResult(0.0, "miss")
112
 
113
 
114
- def _tool_calls() -> int | None:
115
- """Number of agent tool calls this rollout, for the efficiency reward.
116
-
117
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
118
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
119
- (efficiency reward becomes null — the harness didn't report a count).
120
- """
121
  try:
122
  with open("/workdir/.n_tool_calls") as fh:
123
  return int(fh.read().strip())
@@ -132,24 +121,17 @@ def _tool_calls() -> int | None:
132
  return None
133
 
134
 
135
- def _tool_efficiency(n_calls: int | None) -> float | None:
136
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
137
-
138
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
139
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
140
- RL reward combiner decides gating/weights.
141
- """
142
- if n_calls is None:
143
  return None
144
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
145
  if budget <= 0:
146
  return None
147
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
148
 
149
 
150
- def _tols() -> tuple[float, float]:
151
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
152
- def _f(name: str) -> float:
153
  try:
154
  return float(os.environ.get(name, "") or 1e-3)
155
  except ValueError:
@@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]:
158
 
159
 
160
  def main_cli() -> int:
161
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
162
-
163
- Inputs (via env vars set by Harbor's [verifier.env]):
164
- EXPECTED_ANSWER — the gold
165
- QUESTION — the original question
166
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
167
-
168
- Predicted answer is read from stdin.
169
- Single float written to stdout. Exit code is always 0.
170
- """
171
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
172
  question = (os.environ.get("QUESTION") or "").strip()
173
  candidate = sys.stdin.read().strip()
174
  at, rt = _tols()
175
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
176
- print(f"{result.reward:.1f}")
177
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
178
- file=sys.stderr)
179
  return 0
180
 
181
 
182
  def main_json() -> int:
183
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
184
-
185
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
186
- correctness — 1.0 iff graded answer matches gold, else 0.0
187
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
188
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
189
-
190
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
191
- """
192
  import json
193
-
194
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
195
  question = (os.environ.get("QUESTION") or "").strip()
196
  candidate = sys.stdin.read().strip()
197
-
198
  if not candidate:
199
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
200
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
201
  return 0
202
-
203
  at, rt = _tols()
204
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
205
- n_calls = _tool_calls()
206
- eff = _tool_efficiency(n_calls)
207
- print(json.dumps({
208
- "correctness": float(result.reward),
209
- "submission": 1.0,
210
- "tool_efficiency": eff,
211
- }))
212
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
213
- f"correctness={result.reward} method={result.method} "
214
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
215
  return 0
216
 
217
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
17
 
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0001_541_1541002_qa_2/tests/grader.py CHANGED
@@ -1,78 +1,34 @@
1
- """Shared three-tier grader.
2
 
3
- Used by both runtimes:
4
- * `env/server.py` — inline inside the `final_answer` ORS @tool method
5
- * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py
6
- and invoked with `python3 /tests/grader.py < /workdir/answer.txt`
7
-
8
- Tiers (cheapest → most expensive):
9
  1. Exact (case-insensitive, whitespace-collapsed)
10
- 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3)
11
- 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt)
12
- — only invoked if OPENAI_API_KEY is set
13
-
14
- CLI form (used by tests/test.sh):
15
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
16
- → reads predicted answer from stdin
17
- → writes a single float ('1.0' or '0.0') to stdout
18
- → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt
19
  """
20
-
21
  from __future__ import annotations
22
-
23
- import os
24
- import re
25
- import sys
26
  from dataclasses import dataclass
27
 
28
-
29
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
30
 
31
- # Locked in PLAN.md §"Locked decisions" — adapted from
32
- # https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py
33
- JUDGE_PROMPT = """You are grading short answers from a data-science agent.
34
- Decide whether the predicted answer is semantically equivalent to the gold answer.
35
-
36
- Rules:
37
- - Case, punctuation, whitespace, articles ("the"), and trailing units don't matter.
38
- - For numbers: predicted must match to the last significant figure of the gold
39
- (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT).
40
- - Extra surrounding prose is fine if the gold value is clearly stated
41
- (gold "5", predicted "There are 5 distinct categories" -> CORRECT).
42
- - Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT).
43
- - Parenthetical annotations in the gold are equivalence hints, not required
44
- (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT;
45
- gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT).
46
- - Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X%
47
- is CORRECT as long as the core numeric value matches
48
- (gold "21.334% in 2014", predicted "21.334" -> CORRECT;
49
- gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch).
50
- - Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one
51
- thing (e.g. "which model?"), predicting either listed value is CORRECT.
52
- - If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED.
53
- - If it commits to a different value -> INCORRECT.
54
-
55
- Question: {question}
56
- Gold answer: {gold}
57
- Predicted answer: {pred}
58
-
59
- Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED)."""
60
-
61
 
62
  @dataclass
63
  class GradeResult:
64
  reward: float
65
- method: str # "exact" | "numeric" | "llm" | "miss"
66
 
67
 
68
  def _normalize(s: str) -> str:
69
  return re.sub(r"\s+", " ", (s or "").strip().lower())
70
 
71
 
72
- def _to_float(s: str) -> float | None:
73
  if not s:
74
  return None
75
- m = _NUMERIC_RE.search(s.replace(",", ""))
76
  if not m:
77
  return None
78
  try:
@@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None:
81
  return None
82
 
83
 
84
- def _math_verify_match(gold: str, candidate: str) -> bool:
85
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
86
-
87
- Catches equivalences the naive float-parse misses: thousands separators,
88
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
89
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
90
- false positive). No network, no LLM.
91
- """
92
- try:
93
- from math_verify import parse, verify
94
-
95
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
96
- except Exception: # noqa: BLE001
97
- return False
98
 
99
 
100
  def _is_clean_number(s: str) -> bool:
101
- """True iff the whole string IS a single number (allowing a leading/trailing
102
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
103
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
104
- the numeric tier must not fire on it (its `_to_float` would grab the leading
105
- '3' and false-positive-match any answer starting with 3)."""
106
  t = (s or "").strip().strip("%$").strip().replace(",", "")
107
  return bool(_NUMERIC_RE.fullmatch(t))
108
 
109
 
110
- def grade(
111
- gold: str,
112
- candidate: str,
113
- *,
114
- question: str = "",
115
- reward_mode: str = "",
116
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
117
- judge_model: str | None = None, # noqa: ARG001
118
- rel_tol: float = 1e-3,
119
- abs_tol: float = 1e-3,
120
- ) -> GradeResult:
121
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
124
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
125
- """
126
 
 
 
127
  if not gold or candidate is None:
128
  return GradeResult(0.0, "miss")
129
 
130
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
131
  if _normalize(gold) == _normalize(candidate):
132
  return GradeResult(1.0, "exact")
133
 
134
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
135
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
136
- # the leading number; those must go to exact/math_verify, which fail closed).
137
- if reward_mode == "numeric" or _is_clean_number(gold):
138
  g, c = _to_float(gold), _to_float(candidate)
139
  if g is not None and c is not None:
140
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
141
  return GradeResult(1.0, "numeric")
 
 
 
 
142
 
143
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
144
  if _math_verify_match(gold, candidate):
145
  return GradeResult(1.0, "math_verify")
146
 
147
  return GradeResult(0.0, "miss")
148
 
149
 
150
- def _tool_calls() -> int | None:
151
- """Number of agent tool calls this rollout, for the efficiency reward.
152
-
153
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
154
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
155
- (efficiency reward becomes null — the harness didn't report a count).
156
- """
157
  try:
158
  with open("/workdir/.n_tool_calls") as fh:
159
  return int(fh.read().strip())
@@ -168,24 +121,17 @@ def _tool_calls() -> int | None:
168
  return None
169
 
170
 
171
- def _tool_efficiency(n_calls: int | None) -> float | None:
172
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
173
-
174
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
175
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
176
- RL reward combiner decides gating/weights.
177
- """
178
- if n_calls is None:
179
  return None
180
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
181
  if budget <= 0:
182
  return None
183
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
184
 
185
 
186
- def _tols() -> tuple[float, float]:
187
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
188
- def _f(name: str) -> float:
189
  try:
190
  return float(os.environ.get(name, "") or 1e-3)
191
  except ValueError:
@@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]:
194
 
195
 
196
  def main_cli() -> int:
197
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
198
-
199
- Inputs (via env vars set by Harbor's [verifier.env]):
200
- EXPECTED_ANSWER — the gold
201
- QUESTION — the original question
202
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
203
-
204
- Predicted answer is read from stdin.
205
- Single float written to stdout. Exit code is always 0.
206
- """
207
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
208
  question = (os.environ.get("QUESTION") or "").strip()
209
  candidate = sys.stdin.read().strip()
210
  at, rt = _tols()
211
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
212
- print(f"{result.reward:.1f}")
213
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
214
- file=sys.stderr)
215
  return 0
216
 
217
 
218
  def main_json() -> int:
219
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
220
-
221
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
222
- correctness — 1.0 iff graded answer matches gold, else 0.0
223
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
224
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
225
-
226
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
227
- """
228
  import json
229
-
230
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
231
  question = (os.environ.get("QUESTION") or "").strip()
232
  candidate = sys.stdin.read().strip()
233
-
234
  if not candidate:
235
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
236
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
237
  return 0
238
-
239
  at, rt = _tols()
240
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
241
- n_calls = _tool_calls()
242
- eff = _tool_efficiency(n_calls)
243
- print(json.dumps({
244
- "correctness": float(result.reward),
245
- "submission": 1.0,
246
- "tool_efficiency": eff,
247
- }))
248
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
249
- f"correctness={result.reward} method={result.method} "
250
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
251
  return 0
252
 
253
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
 
 
 
 
 
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0001_570_1570948_qa_4/tests/grader.py CHANGED
@@ -1,42 +1,34 @@
1
- """Deterministic short-answer grader — NO LLM judge.
2
 
3
- Tiers (cheapest -> most expensive), all offline/deterministic:
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
- 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
- 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify)
7
-
8
- CLI form (used by tests/test.sh):
9
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
10
- -> reads predicted answer from stdin
11
- -> writes a single float ('1.0' or '0.0') to stdout
12
  """
13
-
14
  from __future__ import annotations
15
-
16
- import os
17
- import re
18
- import sys
19
  from dataclasses import dataclass
20
 
21
-
22
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
23
 
24
 
25
-
26
  @dataclass
27
  class GradeResult:
28
  reward: float
29
- method: str # "exact" | "numeric" | "llm" | "miss"
30
 
31
 
32
  def _normalize(s: str) -> str:
33
  return re.sub(r"\s+", " ", (s or "").strip().lower())
34
 
35
 
36
- def _to_float(s: str) -> float | None:
37
  if not s:
38
  return None
39
- m = _NUMERIC_RE.search(s.replace(",", ""))
40
  if not m:
41
  return None
42
  try:
@@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None:
45
  return None
46
 
47
 
48
- def _math_verify_match(gold: str, candidate: str) -> bool:
49
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
50
-
51
- Catches equivalences the naive float-parse misses: thousands separators,
52
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
53
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
54
- false positive). No network, no LLM.
55
- """
56
- try:
57
- from math_verify import parse, verify
58
-
59
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
60
- except Exception: # noqa: BLE001
61
- return False
62
 
63
 
64
  def _is_clean_number(s: str) -> bool:
65
- """True iff the whole string IS a single number (allowing a leading/trailing
66
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
67
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
68
- the numeric tier must not fire on it (its `_to_float` would grab the leading
69
- '3' and false-positive-match any answer starting with 3)."""
70
  t = (s or "").strip().strip("%$").strip().replace(",", "")
71
  return bool(_NUMERIC_RE.fullmatch(t))
72
 
73
 
74
- def grade(
75
- gold: str,
76
- candidate: str,
77
- *,
78
- question: str = "",
79
- reward_mode: str = "",
80
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
81
- judge_model: str | None = None, # noqa: ARG001
82
- rel_tol: float = 1e-3,
83
- abs_tol: float = 1e-3,
84
- ) -> GradeResult:
85
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
88
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
89
- """
90
 
 
 
91
  if not gold or candidate is None:
92
  return GradeResult(0.0, "miss")
93
 
94
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
95
  if _normalize(gold) == _normalize(candidate):
96
  return GradeResult(1.0, "exact")
97
 
98
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
99
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
100
- # the leading number; those must go to exact/math_verify, which fail closed).
101
- if reward_mode == "numeric" or _is_clean_number(gold):
102
  g, c = _to_float(gold), _to_float(candidate)
103
  if g is not None and c is not None:
104
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
105
  return GradeResult(1.0, "numeric")
 
 
 
 
106
 
107
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
108
  if _math_verify_match(gold, candidate):
109
  return GradeResult(1.0, "math_verify")
110
 
111
  return GradeResult(0.0, "miss")
112
 
113
 
114
- def _tool_calls() -> int | None:
115
- """Number of agent tool calls this rollout, for the efficiency reward.
116
-
117
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
118
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
119
- (efficiency reward becomes null — the harness didn't report a count).
120
- """
121
  try:
122
  with open("/workdir/.n_tool_calls") as fh:
123
  return int(fh.read().strip())
@@ -132,24 +121,17 @@ def _tool_calls() -> int | None:
132
  return None
133
 
134
 
135
- def _tool_efficiency(n_calls: int | None) -> float | None:
136
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
137
-
138
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
139
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
140
- RL reward combiner decides gating/weights.
141
- """
142
- if n_calls is None:
143
  return None
144
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
145
  if budget <= 0:
146
  return None
147
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
148
 
149
 
150
- def _tols() -> tuple[float, float]:
151
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
152
- def _f(name: str) -> float:
153
  try:
154
  return float(os.environ.get(name, "") or 1e-3)
155
  except ValueError:
@@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]:
158
 
159
 
160
  def main_cli() -> int:
161
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
162
-
163
- Inputs (via env vars set by Harbor's [verifier.env]):
164
- EXPECTED_ANSWER — the gold
165
- QUESTION — the original question
166
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
167
-
168
- Predicted answer is read from stdin.
169
- Single float written to stdout. Exit code is always 0.
170
- """
171
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
172
  question = (os.environ.get("QUESTION") or "").strip()
173
  candidate = sys.stdin.read().strip()
174
  at, rt = _tols()
175
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
176
- print(f"{result.reward:.1f}")
177
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
178
- file=sys.stderr)
179
  return 0
180
 
181
 
182
  def main_json() -> int:
183
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
184
-
185
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
186
- correctness — 1.0 iff graded answer matches gold, else 0.0
187
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
188
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
189
-
190
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
191
- """
192
  import json
193
-
194
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
195
  question = (os.environ.get("QUESTION") or "").strip()
196
  candidate = sys.stdin.read().strip()
197
-
198
  if not candidate:
199
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
200
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
201
  return 0
202
-
203
  at, rt = _tols()
204
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
205
- n_calls = _tool_calls()
206
- eff = _tool_efficiency(n_calls)
207
- print(json.dumps({
208
- "correctness": float(result.reward),
209
- "submission": 1.0,
210
- "tool_efficiency": eff,
211
- }))
212
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
213
- f"correctness={result.reward} method={result.method} "
214
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
215
  return 0
216
 
217
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
17
 
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0001_661_1661005_qa_1/tests/grader.py CHANGED
@@ -1,42 +1,34 @@
1
- """Deterministic short-answer grader — NO LLM judge.
2
 
3
- Tiers (cheapest -> most expensive), all offline/deterministic:
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
- 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
- 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify)
7
-
8
- CLI form (used by tests/test.sh):
9
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
10
- -> reads predicted answer from stdin
11
- -> writes a single float ('1.0' or '0.0') to stdout
12
  """
13
-
14
  from __future__ import annotations
15
-
16
- import os
17
- import re
18
- import sys
19
  from dataclasses import dataclass
20
 
21
-
22
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
23
 
24
 
25
-
26
  @dataclass
27
  class GradeResult:
28
  reward: float
29
- method: str # "exact" | "numeric" | "llm" | "miss"
30
 
31
 
32
  def _normalize(s: str) -> str:
33
  return re.sub(r"\s+", " ", (s or "").strip().lower())
34
 
35
 
36
- def _to_float(s: str) -> float | None:
37
  if not s:
38
  return None
39
- m = _NUMERIC_RE.search(s.replace(",", ""))
40
  if not m:
41
  return None
42
  try:
@@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None:
45
  return None
46
 
47
 
48
- def _math_verify_match(gold: str, candidate: str) -> bool:
49
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
50
-
51
- Catches equivalences the naive float-parse misses: thousands separators,
52
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
53
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
54
- false positive). No network, no LLM.
55
- """
56
- try:
57
- from math_verify import parse, verify
58
-
59
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
60
- except Exception: # noqa: BLE001
61
- return False
62
 
63
 
64
  def _is_clean_number(s: str) -> bool:
65
- """True iff the whole string IS a single number (allowing a leading/trailing
66
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
67
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
68
- the numeric tier must not fire on it (its `_to_float` would grab the leading
69
- '3' and false-positive-match any answer starting with 3)."""
70
  t = (s or "").strip().strip("%$").strip().replace(",", "")
71
  return bool(_NUMERIC_RE.fullmatch(t))
72
 
73
 
74
- def grade(
75
- gold: str,
76
- candidate: str,
77
- *,
78
- question: str = "",
79
- reward_mode: str = "",
80
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
81
- judge_model: str | None = None, # noqa: ARG001
82
- rel_tol: float = 1e-3,
83
- abs_tol: float = 1e-3,
84
- ) -> GradeResult:
85
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
88
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
89
- """
90
 
 
 
91
  if not gold or candidate is None:
92
  return GradeResult(0.0, "miss")
93
 
94
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
95
  if _normalize(gold) == _normalize(candidate):
96
  return GradeResult(1.0, "exact")
97
 
98
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
99
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
100
- # the leading number; those must go to exact/math_verify, which fail closed).
101
- if reward_mode == "numeric" or _is_clean_number(gold):
102
  g, c = _to_float(gold), _to_float(candidate)
103
  if g is not None and c is not None:
104
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
105
  return GradeResult(1.0, "numeric")
 
 
 
 
106
 
107
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
108
  if _math_verify_match(gold, candidate):
109
  return GradeResult(1.0, "math_verify")
110
 
111
  return GradeResult(0.0, "miss")
112
 
113
 
114
- def _tool_calls() -> int | None:
115
- """Number of agent tool calls this rollout, for the efficiency reward.
116
-
117
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
118
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
119
- (efficiency reward becomes null — the harness didn't report a count).
120
- """
121
  try:
122
  with open("/workdir/.n_tool_calls") as fh:
123
  return int(fh.read().strip())
@@ -132,24 +121,17 @@ def _tool_calls() -> int | None:
132
  return None
133
 
134
 
135
- def _tool_efficiency(n_calls: int | None) -> float | None:
136
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
137
-
138
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
139
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
140
- RL reward combiner decides gating/weights.
141
- """
142
- if n_calls is None:
143
  return None
144
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
145
  if budget <= 0:
146
  return None
147
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
148
 
149
 
150
- def _tols() -> tuple[float, float]:
151
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
152
- def _f(name: str) -> float:
153
  try:
154
  return float(os.environ.get(name, "") or 1e-3)
155
  except ValueError:
@@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]:
158
 
159
 
160
  def main_cli() -> int:
161
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
162
-
163
- Inputs (via env vars set by Harbor's [verifier.env]):
164
- EXPECTED_ANSWER — the gold
165
- QUESTION — the original question
166
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
167
-
168
- Predicted answer is read from stdin.
169
- Single float written to stdout. Exit code is always 0.
170
- """
171
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
172
  question = (os.environ.get("QUESTION") or "").strip()
173
  candidate = sys.stdin.read().strip()
174
  at, rt = _tols()
175
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
176
- print(f"{result.reward:.1f}")
177
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
178
- file=sys.stderr)
179
  return 0
180
 
181
 
182
  def main_json() -> int:
183
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
184
-
185
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
186
- correctness — 1.0 iff graded answer matches gold, else 0.0
187
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
188
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
189
-
190
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
191
- """
192
  import json
193
-
194
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
195
  question = (os.environ.get("QUESTION") or "").strip()
196
  candidate = sys.stdin.read().strip()
197
-
198
  if not candidate:
199
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
200
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
201
  return 0
202
-
203
  at, rt = _tols()
204
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
205
- n_calls = _tool_calls()
206
- eff = _tool_efficiency(n_calls)
207
- print(json.dumps({
208
- "correctness": float(result.reward),
209
- "submission": 1.0,
210
- "tool_efficiency": eff,
211
- }))
212
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
213
- f"correctness={result.reward} method={result.method} "
214
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
215
  return 0
216
 
217
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
17
 
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0001_666_1666101_qa_5/tests/grader.py CHANGED
@@ -1,42 +1,34 @@
1
- """Deterministic short-answer grader — NO LLM judge.
2
 
3
- Tiers (cheapest -> most expensive), all offline/deterministic:
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
- 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
- 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify)
7
-
8
- CLI form (used by tests/test.sh):
9
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
10
- -> reads predicted answer from stdin
11
- -> writes a single float ('1.0' or '0.0') to stdout
12
  """
13
-
14
  from __future__ import annotations
15
-
16
- import os
17
- import re
18
- import sys
19
  from dataclasses import dataclass
20
 
21
-
22
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
23
 
24
 
25
-
26
  @dataclass
27
  class GradeResult:
28
  reward: float
29
- method: str # "exact" | "numeric" | "llm" | "miss"
30
 
31
 
32
  def _normalize(s: str) -> str:
33
  return re.sub(r"\s+", " ", (s or "").strip().lower())
34
 
35
 
36
- def _to_float(s: str) -> float | None:
37
  if not s:
38
  return None
39
- m = _NUMERIC_RE.search(s.replace(",", ""))
40
  if not m:
41
  return None
42
  try:
@@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None:
45
  return None
46
 
47
 
48
- def _math_verify_match(gold: str, candidate: str) -> bool:
49
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
50
-
51
- Catches equivalences the naive float-parse misses: thousands separators,
52
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
53
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
54
- false positive). No network, no LLM.
55
- """
56
- try:
57
- from math_verify import parse, verify
58
-
59
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
60
- except Exception: # noqa: BLE001
61
- return False
62
 
63
 
64
  def _is_clean_number(s: str) -> bool:
65
- """True iff the whole string IS a single number (allowing a leading/trailing
66
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
67
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
68
- the numeric tier must not fire on it (its `_to_float` would grab the leading
69
- '3' and false-positive-match any answer starting with 3)."""
70
  t = (s or "").strip().strip("%$").strip().replace(",", "")
71
  return bool(_NUMERIC_RE.fullmatch(t))
72
 
73
 
74
- def grade(
75
- gold: str,
76
- candidate: str,
77
- *,
78
- question: str = "",
79
- reward_mode: str = "",
80
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
81
- judge_model: str | None = None, # noqa: ARG001
82
- rel_tol: float = 1e-3,
83
- abs_tol: float = 1e-3,
84
- ) -> GradeResult:
85
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
88
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
89
- """
90
 
 
 
91
  if not gold or candidate is None:
92
  return GradeResult(0.0, "miss")
93
 
94
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
95
  if _normalize(gold) == _normalize(candidate):
96
  return GradeResult(1.0, "exact")
97
 
98
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
99
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
100
- # the leading number; those must go to exact/math_verify, which fail closed).
101
- if reward_mode == "numeric" or _is_clean_number(gold):
102
  g, c = _to_float(gold), _to_float(candidate)
103
  if g is not None and c is not None:
104
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
105
  return GradeResult(1.0, "numeric")
 
 
 
 
106
 
107
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
108
  if _math_verify_match(gold, candidate):
109
  return GradeResult(1.0, "math_verify")
110
 
111
  return GradeResult(0.0, "miss")
112
 
113
 
114
- def _tool_calls() -> int | None:
115
- """Number of agent tool calls this rollout, for the efficiency reward.
116
-
117
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
118
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
119
- (efficiency reward becomes null — the harness didn't report a count).
120
- """
121
  try:
122
  with open("/workdir/.n_tool_calls") as fh:
123
  return int(fh.read().strip())
@@ -132,24 +121,17 @@ def _tool_calls() -> int | None:
132
  return None
133
 
134
 
135
- def _tool_efficiency(n_calls: int | None) -> float | None:
136
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
137
-
138
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
139
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
140
- RL reward combiner decides gating/weights.
141
- """
142
- if n_calls is None:
143
  return None
144
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
145
  if budget <= 0:
146
  return None
147
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
148
 
149
 
150
- def _tols() -> tuple[float, float]:
151
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
152
- def _f(name: str) -> float:
153
  try:
154
  return float(os.environ.get(name, "") or 1e-3)
155
  except ValueError:
@@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]:
158
 
159
 
160
  def main_cli() -> int:
161
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
162
-
163
- Inputs (via env vars set by Harbor's [verifier.env]):
164
- EXPECTED_ANSWER — the gold
165
- QUESTION — the original question
166
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
167
-
168
- Predicted answer is read from stdin.
169
- Single float written to stdout. Exit code is always 0.
170
- """
171
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
172
  question = (os.environ.get("QUESTION") or "").strip()
173
  candidate = sys.stdin.read().strip()
174
  at, rt = _tols()
175
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
176
- print(f"{result.reward:.1f}")
177
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
178
- file=sys.stderr)
179
  return 0
180
 
181
 
182
  def main_json() -> int:
183
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
184
-
185
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
186
- correctness — 1.0 iff graded answer matches gold, else 0.0
187
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
188
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
189
-
190
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
191
- """
192
  import json
193
-
194
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
195
  question = (os.environ.get("QUESTION") or "").strip()
196
  candidate = sys.stdin.read().strip()
197
-
198
  if not candidate:
199
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
200
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
201
  return 0
202
-
203
  at, rt = _tols()
204
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
205
- n_calls = _tool_calls()
206
- eff = _tool_efficiency(n_calls)
207
- print(json.dumps({
208
- "correctness": float(result.reward),
209
- "submission": 1.0,
210
- "tool_efficiency": eff,
211
- }))
212
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
213
- f"correctness={result.reward} method={result.method} "
214
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
215
  return 0
216
 
217
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
17
 
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0001_876_1876377_qa_2/tests/grader.py CHANGED
@@ -1,42 +1,34 @@
1
- """Deterministic short-answer grader — NO LLM judge.
2
 
3
- Tiers (cheapest -> most expensive), all offline/deterministic:
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
- 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
- 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify)
7
-
8
- CLI form (used by tests/test.sh):
9
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
10
- -> reads predicted answer from stdin
11
- -> writes a single float ('1.0' or '0.0') to stdout
12
  """
13
-
14
  from __future__ import annotations
15
-
16
- import os
17
- import re
18
- import sys
19
  from dataclasses import dataclass
20
 
21
-
22
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
23
 
24
 
25
-
26
  @dataclass
27
  class GradeResult:
28
  reward: float
29
- method: str # "exact" | "numeric" | "llm" | "miss"
30
 
31
 
32
  def _normalize(s: str) -> str:
33
  return re.sub(r"\s+", " ", (s or "").strip().lower())
34
 
35
 
36
- def _to_float(s: str) -> float | None:
37
  if not s:
38
  return None
39
- m = _NUMERIC_RE.search(s.replace(",", ""))
40
  if not m:
41
  return None
42
  try:
@@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None:
45
  return None
46
 
47
 
48
- def _math_verify_match(gold: str, candidate: str) -> bool:
49
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
50
-
51
- Catches equivalences the naive float-parse misses: thousands separators,
52
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
53
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
54
- false positive). No network, no LLM.
55
- """
56
- try:
57
- from math_verify import parse, verify
58
-
59
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
60
- except Exception: # noqa: BLE001
61
- return False
62
 
63
 
64
  def _is_clean_number(s: str) -> bool:
65
- """True iff the whole string IS a single number (allowing a leading/trailing
66
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
67
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
68
- the numeric tier must not fire on it (its `_to_float` would grab the leading
69
- '3' and false-positive-match any answer starting with 3)."""
70
  t = (s or "").strip().strip("%$").strip().replace(",", "")
71
  return bool(_NUMERIC_RE.fullmatch(t))
72
 
73
 
74
- def grade(
75
- gold: str,
76
- candidate: str,
77
- *,
78
- question: str = "",
79
- reward_mode: str = "",
80
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
81
- judge_model: str | None = None, # noqa: ARG001
82
- rel_tol: float = 1e-3,
83
- abs_tol: float = 1e-3,
84
- ) -> GradeResult:
85
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
88
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
89
- """
90
 
 
 
91
  if not gold or candidate is None:
92
  return GradeResult(0.0, "miss")
93
 
94
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
95
  if _normalize(gold) == _normalize(candidate):
96
  return GradeResult(1.0, "exact")
97
 
98
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
99
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
100
- # the leading number; those must go to exact/math_verify, which fail closed).
101
- if reward_mode == "numeric" or _is_clean_number(gold):
102
  g, c = _to_float(gold), _to_float(candidate)
103
  if g is not None and c is not None:
104
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
105
  return GradeResult(1.0, "numeric")
 
 
 
 
106
 
107
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
108
  if _math_verify_match(gold, candidate):
109
  return GradeResult(1.0, "math_verify")
110
 
111
  return GradeResult(0.0, "miss")
112
 
113
 
114
- def _tool_calls() -> int | None:
115
- """Number of agent tool calls this rollout, for the efficiency reward.
116
-
117
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
118
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
119
- (efficiency reward becomes null — the harness didn't report a count).
120
- """
121
  try:
122
  with open("/workdir/.n_tool_calls") as fh:
123
  return int(fh.read().strip())
@@ -132,24 +121,17 @@ def _tool_calls() -> int | None:
132
  return None
133
 
134
 
135
- def _tool_efficiency(n_calls: int | None) -> float | None:
136
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
137
-
138
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
139
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
140
- RL reward combiner decides gating/weights.
141
- """
142
- if n_calls is None:
143
  return None
144
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
145
  if budget <= 0:
146
  return None
147
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
148
 
149
 
150
- def _tols() -> tuple[float, float]:
151
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
152
- def _f(name: str) -> float:
153
  try:
154
  return float(os.environ.get(name, "") or 1e-3)
155
  except ValueError:
@@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]:
158
 
159
 
160
  def main_cli() -> int:
161
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
162
-
163
- Inputs (via env vars set by Harbor's [verifier.env]):
164
- EXPECTED_ANSWER — the gold
165
- QUESTION — the original question
166
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
167
-
168
- Predicted answer is read from stdin.
169
- Single float written to stdout. Exit code is always 0.
170
- """
171
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
172
  question = (os.environ.get("QUESTION") or "").strip()
173
  candidate = sys.stdin.read().strip()
174
  at, rt = _tols()
175
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
176
- print(f"{result.reward:.1f}")
177
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
178
- file=sys.stderr)
179
  return 0
180
 
181
 
182
  def main_json() -> int:
183
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
184
-
185
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
186
- correctness — 1.0 iff graded answer matches gold, else 0.0
187
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
188
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
189
-
190
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
191
- """
192
  import json
193
-
194
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
195
  question = (os.environ.get("QUESTION") or "").strip()
196
  candidate = sys.stdin.read().strip()
197
-
198
  if not candidate:
199
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
200
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
201
  return 0
202
-
203
  at, rt = _tols()
204
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
205
- n_calls = _tool_calls()
206
- eff = _tool_efficiency(n_calls)
207
- print(json.dumps({
208
- "correctness": float(result.reward),
209
- "submission": 1.0,
210
- "tool_efficiency": eff,
211
- }))
212
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
213
- f"correctness={result.reward} method={result.method} "
214
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
215
  return 0
216
 
217
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
17
 
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0001_959_1959663_qa_3/tests/grader.py CHANGED
@@ -1,78 +1,34 @@
1
- """Shared three-tier grader.
2
 
3
- Used by both runtimes:
4
- * `env/server.py` — inline inside the `final_answer` ORS @tool method
5
- * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py
6
- and invoked with `python3 /tests/grader.py < /workdir/answer.txt`
7
-
8
- Tiers (cheapest → most expensive):
9
  1. Exact (case-insensitive, whitespace-collapsed)
10
- 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3)
11
- 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt)
12
- — only invoked if OPENAI_API_KEY is set
13
-
14
- CLI form (used by tests/test.sh):
15
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
16
- → reads predicted answer from stdin
17
- → writes a single float ('1.0' or '0.0') to stdout
18
- → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt
19
  """
20
-
21
  from __future__ import annotations
22
-
23
- import os
24
- import re
25
- import sys
26
  from dataclasses import dataclass
27
 
28
-
29
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
30
 
31
- # Locked in PLAN.md §"Locked decisions" — adapted from
32
- # https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py
33
- JUDGE_PROMPT = """You are grading short answers from a data-science agent.
34
- Decide whether the predicted answer is semantically equivalent to the gold answer.
35
-
36
- Rules:
37
- - Case, punctuation, whitespace, articles ("the"), and trailing units don't matter.
38
- - For numbers: predicted must match to the last significant figure of the gold
39
- (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT).
40
- - Extra surrounding prose is fine if the gold value is clearly stated
41
- (gold "5", predicted "There are 5 distinct categories" -> CORRECT).
42
- - Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT).
43
- - Parenthetical annotations in the gold are equivalence hints, not required
44
- (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT;
45
- gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT).
46
- - Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X%
47
- is CORRECT as long as the core numeric value matches
48
- (gold "21.334% in 2014", predicted "21.334" -> CORRECT;
49
- gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch).
50
- - Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one
51
- thing (e.g. "which model?"), predicting either listed value is CORRECT.
52
- - If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED.
53
- - If it commits to a different value -> INCORRECT.
54
-
55
- Question: {question}
56
- Gold answer: {gold}
57
- Predicted answer: {pred}
58
-
59
- Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED)."""
60
-
61
 
62
  @dataclass
63
  class GradeResult:
64
  reward: float
65
- method: str # "exact" | "numeric" | "llm" | "miss"
66
 
67
 
68
  def _normalize(s: str) -> str:
69
  return re.sub(r"\s+", " ", (s or "").strip().lower())
70
 
71
 
72
- def _to_float(s: str) -> float | None:
73
  if not s:
74
  return None
75
- m = _NUMERIC_RE.search(s.replace(",", ""))
76
  if not m:
77
  return None
78
  try:
@@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None:
81
  return None
82
 
83
 
84
- def _math_verify_match(gold: str, candidate: str) -> bool:
85
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
86
-
87
- Catches equivalences the naive float-parse misses: thousands separators,
88
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
89
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
90
- false positive). No network, no LLM.
91
- """
92
- try:
93
- from math_verify import parse, verify
94
-
95
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
96
- except Exception: # noqa: BLE001
97
- return False
98
 
99
 
100
  def _is_clean_number(s: str) -> bool:
101
- """True iff the whole string IS a single number (allowing a leading/trailing
102
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
103
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
104
- the numeric tier must not fire on it (its `_to_float` would grab the leading
105
- '3' and false-positive-match any answer starting with 3)."""
106
  t = (s or "").strip().strip("%$").strip().replace(",", "")
107
  return bool(_NUMERIC_RE.fullmatch(t))
108
 
109
 
110
- def grade(
111
- gold: str,
112
- candidate: str,
113
- *,
114
- question: str = "",
115
- reward_mode: str = "",
116
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
117
- judge_model: str | None = None, # noqa: ARG001
118
- rel_tol: float = 1e-3,
119
- abs_tol: float = 1e-3,
120
- ) -> GradeResult:
121
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
124
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
125
- """
126
 
 
 
127
  if not gold or candidate is None:
128
  return GradeResult(0.0, "miss")
129
 
130
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
131
  if _normalize(gold) == _normalize(candidate):
132
  return GradeResult(1.0, "exact")
133
 
134
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
135
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
136
- # the leading number; those must go to exact/math_verify, which fail closed).
137
- if reward_mode == "numeric" or _is_clean_number(gold):
138
  g, c = _to_float(gold), _to_float(candidate)
139
  if g is not None and c is not None:
140
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
141
  return GradeResult(1.0, "numeric")
 
 
 
 
142
 
143
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
144
  if _math_verify_match(gold, candidate):
145
  return GradeResult(1.0, "math_verify")
146
 
147
  return GradeResult(0.0, "miss")
148
 
149
 
150
- def _tool_calls() -> int | None:
151
- """Number of agent tool calls this rollout, for the efficiency reward.
152
-
153
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
154
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
155
- (efficiency reward becomes null — the harness didn't report a count).
156
- """
157
  try:
158
  with open("/workdir/.n_tool_calls") as fh:
159
  return int(fh.read().strip())
@@ -168,24 +121,17 @@ def _tool_calls() -> int | None:
168
  return None
169
 
170
 
171
- def _tool_efficiency(n_calls: int | None) -> float | None:
172
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
173
-
174
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
175
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
176
- RL reward combiner decides gating/weights.
177
- """
178
- if n_calls is None:
179
  return None
180
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
181
  if budget <= 0:
182
  return None
183
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
184
 
185
 
186
- def _tols() -> tuple[float, float]:
187
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
188
- def _f(name: str) -> float:
189
  try:
190
  return float(os.environ.get(name, "") or 1e-3)
191
  except ValueError:
@@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]:
194
 
195
 
196
  def main_cli() -> int:
197
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
198
-
199
- Inputs (via env vars set by Harbor's [verifier.env]):
200
- EXPECTED_ANSWER — the gold
201
- QUESTION — the original question
202
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
203
-
204
- Predicted answer is read from stdin.
205
- Single float written to stdout. Exit code is always 0.
206
- """
207
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
208
  question = (os.environ.get("QUESTION") or "").strip()
209
  candidate = sys.stdin.read().strip()
210
  at, rt = _tols()
211
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
212
- print(f"{result.reward:.1f}")
213
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
214
- file=sys.stderr)
215
  return 0
216
 
217
 
218
  def main_json() -> int:
219
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
220
-
221
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
222
- correctness — 1.0 iff graded answer matches gold, else 0.0
223
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
224
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
225
-
226
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
227
- """
228
  import json
229
-
230
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
231
  question = (os.environ.get("QUESTION") or "").strip()
232
  candidate = sys.stdin.read().strip()
233
-
234
  if not candidate:
235
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
236
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
237
  return 0
238
-
239
  at, rt = _tols()
240
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
241
- n_calls = _tool_calls()
242
- eff = _tool_efficiency(n_calls)
243
- print(json.dumps({
244
- "correctness": float(result.reward),
245
- "submission": 1.0,
246
- "tool_efficiency": eff,
247
- }))
248
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
249
- f"correctness={result.reward} method={result.method} "
250
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
251
  return 0
252
 
253
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
 
 
 
 
 
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0002_094_2094844_qa_1/tests/grader.py CHANGED
@@ -1,42 +1,34 @@
1
- """Deterministic short-answer grader — NO LLM judge.
2
 
3
- Tiers (cheapest -> most expensive), all offline/deterministic:
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
- 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
- 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify)
7
-
8
- CLI form (used by tests/test.sh):
9
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
10
- -> reads predicted answer from stdin
11
- -> writes a single float ('1.0' or '0.0') to stdout
12
  """
13
-
14
  from __future__ import annotations
15
-
16
- import os
17
- import re
18
- import sys
19
  from dataclasses import dataclass
20
 
21
-
22
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
23
 
24
 
25
-
26
  @dataclass
27
  class GradeResult:
28
  reward: float
29
- method: str # "exact" | "numeric" | "llm" | "miss"
30
 
31
 
32
  def _normalize(s: str) -> str:
33
  return re.sub(r"\s+", " ", (s or "").strip().lower())
34
 
35
 
36
- def _to_float(s: str) -> float | None:
37
  if not s:
38
  return None
39
- m = _NUMERIC_RE.search(s.replace(",", ""))
40
  if not m:
41
  return None
42
  try:
@@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None:
45
  return None
46
 
47
 
48
- def _math_verify_match(gold: str, candidate: str) -> bool:
49
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
50
-
51
- Catches equivalences the naive float-parse misses: thousands separators,
52
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
53
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
54
- false positive). No network, no LLM.
55
- """
56
- try:
57
- from math_verify import parse, verify
58
-
59
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
60
- except Exception: # noqa: BLE001
61
- return False
62
 
63
 
64
  def _is_clean_number(s: str) -> bool:
65
- """True iff the whole string IS a single number (allowing a leading/trailing
66
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
67
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
68
- the numeric tier must not fire on it (its `_to_float` would grab the leading
69
- '3' and false-positive-match any answer starting with 3)."""
70
  t = (s or "").strip().strip("%$").strip().replace(",", "")
71
  return bool(_NUMERIC_RE.fullmatch(t))
72
 
73
 
74
- def grade(
75
- gold: str,
76
- candidate: str,
77
- *,
78
- question: str = "",
79
- reward_mode: str = "",
80
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
81
- judge_model: str | None = None, # noqa: ARG001
82
- rel_tol: float = 1e-3,
83
- abs_tol: float = 1e-3,
84
- ) -> GradeResult:
85
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
88
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
89
- """
90
 
 
 
91
  if not gold or candidate is None:
92
  return GradeResult(0.0, "miss")
93
 
94
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
95
  if _normalize(gold) == _normalize(candidate):
96
  return GradeResult(1.0, "exact")
97
 
98
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
99
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
100
- # the leading number; those must go to exact/math_verify, which fail closed).
101
- if reward_mode == "numeric" or _is_clean_number(gold):
102
  g, c = _to_float(gold), _to_float(candidate)
103
  if g is not None and c is not None:
104
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
105
  return GradeResult(1.0, "numeric")
 
 
 
 
106
 
107
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
108
  if _math_verify_match(gold, candidate):
109
  return GradeResult(1.0, "math_verify")
110
 
111
  return GradeResult(0.0, "miss")
112
 
113
 
114
- def _tool_calls() -> int | None:
115
- """Number of agent tool calls this rollout, for the efficiency reward.
116
-
117
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
118
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
119
- (efficiency reward becomes null — the harness didn't report a count).
120
- """
121
  try:
122
  with open("/workdir/.n_tool_calls") as fh:
123
  return int(fh.read().strip())
@@ -132,24 +121,17 @@ def _tool_calls() -> int | None:
132
  return None
133
 
134
 
135
- def _tool_efficiency(n_calls: int | None) -> float | None:
136
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
137
-
138
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
139
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
140
- RL reward combiner decides gating/weights.
141
- """
142
- if n_calls is None:
143
  return None
144
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
145
  if budget <= 0:
146
  return None
147
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
148
 
149
 
150
- def _tols() -> tuple[float, float]:
151
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
152
- def _f(name: str) -> float:
153
  try:
154
  return float(os.environ.get(name, "") or 1e-3)
155
  except ValueError:
@@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]:
158
 
159
 
160
  def main_cli() -> int:
161
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
162
-
163
- Inputs (via env vars set by Harbor's [verifier.env]):
164
- EXPECTED_ANSWER — the gold
165
- QUESTION — the original question
166
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
167
-
168
- Predicted answer is read from stdin.
169
- Single float written to stdout. Exit code is always 0.
170
- """
171
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
172
  question = (os.environ.get("QUESTION") or "").strip()
173
  candidate = sys.stdin.read().strip()
174
  at, rt = _tols()
175
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
176
- print(f"{result.reward:.1f}")
177
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
178
- file=sys.stderr)
179
  return 0
180
 
181
 
182
  def main_json() -> int:
183
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
184
-
185
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
186
- correctness — 1.0 iff graded answer matches gold, else 0.0
187
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
188
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
189
-
190
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
191
- """
192
  import json
193
-
194
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
195
  question = (os.environ.get("QUESTION") or "").strip()
196
  candidate = sys.stdin.read().strip()
197
-
198
  if not candidate:
199
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
200
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
201
  return 0
202
-
203
  at, rt = _tols()
204
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
205
- n_calls = _tool_calls()
206
- eff = _tool_efficiency(n_calls)
207
- print(json.dumps({
208
- "correctness": float(result.reward),
209
- "submission": 1.0,
210
- "tool_efficiency": eff,
211
- }))
212
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
213
- f"correctness={result.reward} method={result.method} "
214
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
215
  return 0
216
 
217
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
17
 
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0002_203_2203940_qa_5/environment/Dockerfile ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ FROM docker.io/savatar101/env-data-agent-train:base
2
+ WORKDIR /workdir
tasks/0002_203_2203940_qa_5/environment/pull_bucket.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pull this task's bucket prefix into /home/user/input/.
2
+
3
+ Invoked by Harbor's [environment.healthcheck] command (declared in task.toml)
4
+ — runs after container start, before the agent. Idempotent: skips work if
5
+ files are already present from a prior pull.
6
+ """
7
+
8
+ import os
9
+ import sys
10
+ from pathlib import Path
11
+
12
+ from huggingface_hub import download_bucket_files, list_bucket_tree
13
+
14
+
15
+ def main() -> int:
16
+ bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all"
17
+ prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/"
18
+ dest = Path("/home/user/input")
19
+ dest.mkdir(parents=True, exist_ok=True)
20
+
21
+ existing = [p for p in dest.iterdir() if p.is_file()]
22
+ if existing:
23
+ print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True)
24
+ return 0
25
+
26
+ targets = [
27
+ (it.path, str(dest / Path(it.path).name))
28
+ for it in list_bucket_tree(bucket, prefix=prefix, recursive=True)
29
+ if getattr(it, "type", None) == "file"
30
+ ]
31
+ if not targets:
32
+ print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True)
33
+ return 2
34
+
35
+ download_bucket_files(bucket, files=targets)
36
+ print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True)
37
+ return 0
38
+
39
+
40
+ if __name__ == "__main__":
41
+ sys.exit(main())
tasks/0002_203_2203940_qa_5/tests/grader.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
+
3
+ Tiers (all offline/deterministic):
4
+ 1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
10
+ """
11
+ from __future__ import annotations
12
+ import os, re, sys
13
+ from dataclasses import dataclass
14
+
15
+ _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
+
17
+
18
+ @dataclass
19
+ class GradeResult:
20
+ reward: float
21
+ method: str
22
+
23
+
24
+ def _normalize(s: str) -> str:
25
+ return re.sub(r"\s+", " ", (s or "").strip().lower())
26
+
27
+
28
+ def _to_float(s: str):
29
+ if not s:
30
+ return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
+ if not m:
33
+ return None
34
+ try:
35
+ return float(m.group(0))
36
+ except ValueError:
37
+ return None
38
+
39
+
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
42
+
43
+
44
+ def _is_clean_number(s: str) -> bool:
45
+ t = (s or "").strip().strip("%$").strip().replace(",", "")
46
+ return bool(_NUMERIC_RE.fullmatch(t))
47
+
48
+
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
+
76
+
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
+ if not gold or candidate is None:
80
+ return GradeResult(0.0, "miss")
81
+
82
+ # Tier 1: exact
83
+ if _normalize(gold) == _normalize(candidate):
84
+ return GradeResult(1.0, "exact")
85
+
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
88
+ g, c = _to_float(gold), _to_float(candidate)
89
+ if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
+ return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
+
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
+ if _math_verify_match(gold, candidate):
104
+ return GradeResult(1.0, "math_verify")
105
+
106
+ return GradeResult(0.0, "miss")
107
+
108
+
109
+ def _tool_calls():
110
+ try:
111
+ with open("/workdir/.n_tool_calls") as fh:
112
+ return int(fh.read().strip())
113
+ except (OSError, ValueError):
114
+ pass
115
+ raw = os.environ.get("N_TOOL_CALLS")
116
+ if raw is not None:
117
+ try:
118
+ return int(str(raw).strip())
119
+ except ValueError:
120
+ return None
121
+ return None
122
+
123
+
124
+ def _tool_efficiency(n):
125
+ if n is None:
126
+ return None
127
+ budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
+ if budget <= 0:
129
+ return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
+
132
+
133
+ def _tols():
134
+ def _f(name):
135
+ try:
136
+ return float(os.environ.get(name, "") or 1e-3)
137
+ except ValueError:
138
+ return 1e-3
139
+ return _f("ATOL"), _f("RTOL")
140
+
141
+
142
+ def main_cli() -> int:
143
+ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
+ question = (os.environ.get("QUESTION") or "").strip()
145
+ candidate = sys.stdin.read().strip()
146
+ at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
150
+ return 0
151
+
152
+
153
+ def main_json() -> int:
154
+ import json
155
+ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
+ question = (os.environ.get("QUESTION") or "").strip()
157
+ candidate = sys.stdin.read().strip()
158
+ if not candidate:
159
+ print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
160
+ return 0
161
+ at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
166
+ return 0
167
+
168
+
169
+ if __name__ == "__main__":
170
+ if "--json" in sys.argv[1:]:
171
+ raise SystemExit(main_json())
172
+ raise SystemExit(main_cli())
tasks/0002_203_2203940_qa_5/tests/test.sh ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -u
3
+ mkdir -p /logs/verifier
4
+
5
+ answer_path="/workdir/answer.txt"
6
+ if [ ! -s "$answer_path" ]; then
7
+ echo "0.0" > /logs/verifier/reward.txt
8
+ echo "[grader] no answer at $answer_path" >&2
9
+ exit 0
10
+ fi
11
+
12
+ pip install --quiet math-verify >/dev/null 2>&1 || true
13
+ python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt
tasks/0002_219_2219893_qa_3/tests/grader.py CHANGED
@@ -1,42 +1,34 @@
1
- """Deterministic short-answer grader — NO LLM judge.
2
 
3
- Tiers (cheapest -> most expensive), all offline/deterministic:
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
- 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
- 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify)
7
-
8
- CLI form (used by tests/test.sh):
9
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
10
- -> reads predicted answer from stdin
11
- -> writes a single float ('1.0' or '0.0') to stdout
12
  """
13
-
14
  from __future__ import annotations
15
-
16
- import os
17
- import re
18
- import sys
19
  from dataclasses import dataclass
20
 
21
-
22
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
23
 
24
 
25
-
26
  @dataclass
27
  class GradeResult:
28
  reward: float
29
- method: str # "exact" | "numeric" | "llm" | "miss"
30
 
31
 
32
  def _normalize(s: str) -> str:
33
  return re.sub(r"\s+", " ", (s or "").strip().lower())
34
 
35
 
36
- def _to_float(s: str) -> float | None:
37
  if not s:
38
  return None
39
- m = _NUMERIC_RE.search(s.replace(",", ""))
40
  if not m:
41
  return None
42
  try:
@@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None:
45
  return None
46
 
47
 
48
- def _math_verify_match(gold: str, candidate: str) -> bool:
49
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
50
-
51
- Catches equivalences the naive float-parse misses: thousands separators,
52
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
53
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
54
- false positive). No network, no LLM.
55
- """
56
- try:
57
- from math_verify import parse, verify
58
-
59
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
60
- except Exception: # noqa: BLE001
61
- return False
62
 
63
 
64
  def _is_clean_number(s: str) -> bool:
65
- """True iff the whole string IS a single number (allowing a leading/trailing
66
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
67
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
68
- the numeric tier must not fire on it (its `_to_float` would grab the leading
69
- '3' and false-positive-match any answer starting with 3)."""
70
  t = (s or "").strip().strip("%$").strip().replace(",", "")
71
  return bool(_NUMERIC_RE.fullmatch(t))
72
 
73
 
74
- def grade(
75
- gold: str,
76
- candidate: str,
77
- *,
78
- question: str = "",
79
- reward_mode: str = "",
80
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
81
- judge_model: str | None = None, # noqa: ARG001
82
- rel_tol: float = 1e-3,
83
- abs_tol: float = 1e-3,
84
- ) -> GradeResult:
85
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
88
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
89
- """
90
 
 
 
91
  if not gold or candidate is None:
92
  return GradeResult(0.0, "miss")
93
 
94
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
95
  if _normalize(gold) == _normalize(candidate):
96
  return GradeResult(1.0, "exact")
97
 
98
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
99
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
100
- # the leading number; those must go to exact/math_verify, which fail closed).
101
- if reward_mode == "numeric" or _is_clean_number(gold):
102
  g, c = _to_float(gold), _to_float(candidate)
103
  if g is not None and c is not None:
104
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
105
  return GradeResult(1.0, "numeric")
 
 
 
 
106
 
107
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
108
  if _math_verify_match(gold, candidate):
109
  return GradeResult(1.0, "math_verify")
110
 
111
  return GradeResult(0.0, "miss")
112
 
113
 
114
- def _tool_calls() -> int | None:
115
- """Number of agent tool calls this rollout, for the efficiency reward.
116
-
117
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
118
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
119
- (efficiency reward becomes null — the harness didn't report a count).
120
- """
121
  try:
122
  with open("/workdir/.n_tool_calls") as fh:
123
  return int(fh.read().strip())
@@ -132,24 +121,17 @@ def _tool_calls() -> int | None:
132
  return None
133
 
134
 
135
- def _tool_efficiency(n_calls: int | None) -> float | None:
136
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
137
-
138
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
139
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
140
- RL reward combiner decides gating/weights.
141
- """
142
- if n_calls is None:
143
  return None
144
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
145
  if budget <= 0:
146
  return None
147
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
148
 
149
 
150
- def _tols() -> tuple[float, float]:
151
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
152
- def _f(name: str) -> float:
153
  try:
154
  return float(os.environ.get(name, "") or 1e-3)
155
  except ValueError:
@@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]:
158
 
159
 
160
  def main_cli() -> int:
161
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
162
-
163
- Inputs (via env vars set by Harbor's [verifier.env]):
164
- EXPECTED_ANSWER — the gold
165
- QUESTION — the original question
166
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
167
-
168
- Predicted answer is read from stdin.
169
- Single float written to stdout. Exit code is always 0.
170
- """
171
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
172
  question = (os.environ.get("QUESTION") or "").strip()
173
  candidate = sys.stdin.read().strip()
174
  at, rt = _tols()
175
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
176
- print(f"{result.reward:.1f}")
177
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
178
- file=sys.stderr)
179
  return 0
180
 
181
 
182
  def main_json() -> int:
183
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
184
-
185
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
186
- correctness — 1.0 iff graded answer matches gold, else 0.0
187
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
188
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
189
-
190
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
191
- """
192
  import json
193
-
194
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
195
  question = (os.environ.get("QUESTION") or "").strip()
196
  candidate = sys.stdin.read().strip()
197
-
198
  if not candidate:
199
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
200
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
201
  return 0
202
-
203
  at, rt = _tols()
204
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
205
- n_calls = _tool_calls()
206
- eff = _tool_efficiency(n_calls)
207
- print(json.dumps({
208
- "correctness": float(result.reward),
209
- "submission": 1.0,
210
- "tool_efficiency": eff,
211
- }))
212
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
213
- f"correctness={result.reward} method={result.method} "
214
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
215
  return 0
216
 
217
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
17
 
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0010_909_10909980_qa_3/tests/grader.py CHANGED
@@ -1,78 +1,34 @@
1
- """Shared three-tier grader.
2
 
3
- Used by both runtimes:
4
- * `env/server.py` — inline inside the `final_answer` ORS @tool method
5
- * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py
6
- and invoked with `python3 /tests/grader.py < /workdir/answer.txt`
7
-
8
- Tiers (cheapest → most expensive):
9
  1. Exact (case-insensitive, whitespace-collapsed)
10
- 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3)
11
- 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt)
12
- — only invoked if OPENAI_API_KEY is set
13
-
14
- CLI form (used by tests/test.sh):
15
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
16
- → reads predicted answer from stdin
17
- → writes a single float ('1.0' or '0.0') to stdout
18
- → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt
19
  """
20
-
21
  from __future__ import annotations
22
-
23
- import os
24
- import re
25
- import sys
26
  from dataclasses import dataclass
27
 
28
-
29
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
30
 
31
- # Locked in PLAN.md §"Locked decisions" — adapted from
32
- # https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py
33
- JUDGE_PROMPT = """You are grading short answers from a data-science agent.
34
- Decide whether the predicted answer is semantically equivalent to the gold answer.
35
-
36
- Rules:
37
- - Case, punctuation, whitespace, articles ("the"), and trailing units don't matter.
38
- - For numbers: predicted must match to the last significant figure of the gold
39
- (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT).
40
- - Extra surrounding prose is fine if the gold value is clearly stated
41
- (gold "5", predicted "There are 5 distinct categories" -> CORRECT).
42
- - Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT).
43
- - Parenthetical annotations in the gold are equivalence hints, not required
44
- (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT;
45
- gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT).
46
- - Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X%
47
- is CORRECT as long as the core numeric value matches
48
- (gold "21.334% in 2014", predicted "21.334" -> CORRECT;
49
- gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch).
50
- - Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one
51
- thing (e.g. "which model?"), predicting either listed value is CORRECT.
52
- - If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED.
53
- - If it commits to a different value -> INCORRECT.
54
-
55
- Question: {question}
56
- Gold answer: {gold}
57
- Predicted answer: {pred}
58
-
59
- Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED)."""
60
-
61
 
62
  @dataclass
63
  class GradeResult:
64
  reward: float
65
- method: str # "exact" | "numeric" | "llm" | "miss"
66
 
67
 
68
  def _normalize(s: str) -> str:
69
  return re.sub(r"\s+", " ", (s or "").strip().lower())
70
 
71
 
72
- def _to_float(s: str) -> float | None:
73
  if not s:
74
  return None
75
- m = _NUMERIC_RE.search(s.replace(",", ""))
76
  if not m:
77
  return None
78
  try:
@@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None:
81
  return None
82
 
83
 
84
- def _math_verify_match(gold: str, candidate: str) -> bool:
85
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
86
-
87
- Catches equivalences the naive float-parse misses: thousands separators,
88
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
89
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
90
- false positive). No network, no LLM.
91
- """
92
- try:
93
- from math_verify import parse, verify
94
-
95
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
96
- except Exception: # noqa: BLE001
97
- return False
98
 
99
 
100
  def _is_clean_number(s: str) -> bool:
101
- """True iff the whole string IS a single number (allowing a leading/trailing
102
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
103
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
104
- the numeric tier must not fire on it (its `_to_float` would grab the leading
105
- '3' and false-positive-match any answer starting with 3)."""
106
  t = (s or "").strip().strip("%$").strip().replace(",", "")
107
  return bool(_NUMERIC_RE.fullmatch(t))
108
 
109
 
110
- def grade(
111
- gold: str,
112
- candidate: str,
113
- *,
114
- question: str = "",
115
- reward_mode: str = "",
116
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
117
- judge_model: str | None = None, # noqa: ARG001
118
- rel_tol: float = 1e-3,
119
- abs_tol: float = 1e-3,
120
- ) -> GradeResult:
121
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
124
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
125
- """
126
 
 
 
127
  if not gold or candidate is None:
128
  return GradeResult(0.0, "miss")
129
 
130
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
131
  if _normalize(gold) == _normalize(candidate):
132
  return GradeResult(1.0, "exact")
133
 
134
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
135
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
136
- # the leading number; those must go to exact/math_verify, which fail closed).
137
- if reward_mode == "numeric" or _is_clean_number(gold):
138
  g, c = _to_float(gold), _to_float(candidate)
139
  if g is not None and c is not None:
140
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
141
  return GradeResult(1.0, "numeric")
 
 
 
 
142
 
143
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
144
  if _math_verify_match(gold, candidate):
145
  return GradeResult(1.0, "math_verify")
146
 
147
  return GradeResult(0.0, "miss")
148
 
149
 
150
- def _tool_calls() -> int | None:
151
- """Number of agent tool calls this rollout, for the efficiency reward.
152
-
153
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
154
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
155
- (efficiency reward becomes null — the harness didn't report a count).
156
- """
157
  try:
158
  with open("/workdir/.n_tool_calls") as fh:
159
  return int(fh.read().strip())
@@ -168,24 +121,17 @@ def _tool_calls() -> int | None:
168
  return None
169
 
170
 
171
- def _tool_efficiency(n_calls: int | None) -> float | None:
172
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
173
-
174
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
175
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
176
- RL reward combiner decides gating/weights.
177
- """
178
- if n_calls is None:
179
  return None
180
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
181
  if budget <= 0:
182
  return None
183
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
184
 
185
 
186
- def _tols() -> tuple[float, float]:
187
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
188
- def _f(name: str) -> float:
189
  try:
190
  return float(os.environ.get(name, "") or 1e-3)
191
  except ValueError:
@@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]:
194
 
195
 
196
  def main_cli() -> int:
197
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
198
-
199
- Inputs (via env vars set by Harbor's [verifier.env]):
200
- EXPECTED_ANSWER — the gold
201
- QUESTION — the original question
202
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
203
-
204
- Predicted answer is read from stdin.
205
- Single float written to stdout. Exit code is always 0.
206
- """
207
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
208
  question = (os.environ.get("QUESTION") or "").strip()
209
  candidate = sys.stdin.read().strip()
210
  at, rt = _tols()
211
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
212
- print(f"{result.reward:.1f}")
213
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
214
- file=sys.stderr)
215
  return 0
216
 
217
 
218
  def main_json() -> int:
219
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
220
-
221
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
222
- correctness — 1.0 iff graded answer matches gold, else 0.0
223
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
224
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
225
-
226
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
227
- """
228
  import json
229
-
230
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
231
  question = (os.environ.get("QUESTION") or "").strip()
232
  candidate = sys.stdin.read().strip()
233
-
234
  if not candidate:
235
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
236
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
237
  return 0
238
-
239
  at, rt = _tols()
240
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
241
- n_calls = _tool_calls()
242
- eff = _tool_efficiency(n_calls)
243
- print(json.dumps({
244
- "correctness": float(result.reward),
245
- "submission": 1.0,
246
- "tool_efficiency": eff,
247
- }))
248
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
249
- f"correctness={result.reward} method={result.method} "
250
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
251
  return 0
252
 
253
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
 
 
 
 
 
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0011_970_11970593_qa_2/tests/grader.py CHANGED
@@ -1,78 +1,34 @@
1
- """Shared three-tier grader.
2
 
3
- Used by both runtimes:
4
- * `env/server.py` — inline inside the `final_answer` ORS @tool method
5
- * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py
6
- and invoked with `python3 /tests/grader.py < /workdir/answer.txt`
7
-
8
- Tiers (cheapest → most expensive):
9
  1. Exact (case-insensitive, whitespace-collapsed)
10
- 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3)
11
- 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt)
12
- — only invoked if OPENAI_API_KEY is set
13
-
14
- CLI form (used by tests/test.sh):
15
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
16
- → reads predicted answer from stdin
17
- → writes a single float ('1.0' or '0.0') to stdout
18
- → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt
19
  """
20
-
21
  from __future__ import annotations
22
-
23
- import os
24
- import re
25
- import sys
26
  from dataclasses import dataclass
27
 
28
-
29
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
30
 
31
- # Locked in PLAN.md §"Locked decisions" — adapted from
32
- # https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py
33
- JUDGE_PROMPT = """You are grading short answers from a data-science agent.
34
- Decide whether the predicted answer is semantically equivalent to the gold answer.
35
-
36
- Rules:
37
- - Case, punctuation, whitespace, articles ("the"), and trailing units don't matter.
38
- - For numbers: predicted must match to the last significant figure of the gold
39
- (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT).
40
- - Extra surrounding prose is fine if the gold value is clearly stated
41
- (gold "5", predicted "There are 5 distinct categories" -> CORRECT).
42
- - Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT).
43
- - Parenthetical annotations in the gold are equivalence hints, not required
44
- (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT;
45
- gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT).
46
- - Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X%
47
- is CORRECT as long as the core numeric value matches
48
- (gold "21.334% in 2014", predicted "21.334" -> CORRECT;
49
- gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch).
50
- - Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one
51
- thing (e.g. "which model?"), predicting either listed value is CORRECT.
52
- - If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED.
53
- - If it commits to a different value -> INCORRECT.
54
-
55
- Question: {question}
56
- Gold answer: {gold}
57
- Predicted answer: {pred}
58
-
59
- Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED)."""
60
-
61
 
62
  @dataclass
63
  class GradeResult:
64
  reward: float
65
- method: str # "exact" | "numeric" | "llm" | "miss"
66
 
67
 
68
  def _normalize(s: str) -> str:
69
  return re.sub(r"\s+", " ", (s or "").strip().lower())
70
 
71
 
72
- def _to_float(s: str) -> float | None:
73
  if not s:
74
  return None
75
- m = _NUMERIC_RE.search(s.replace(",", ""))
76
  if not m:
77
  return None
78
  try:
@@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None:
81
  return None
82
 
83
 
84
- def _math_verify_match(gold: str, candidate: str) -> bool:
85
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
86
-
87
- Catches equivalences the naive float-parse misses: thousands separators,
88
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
89
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
90
- false positive). No network, no LLM.
91
- """
92
- try:
93
- from math_verify import parse, verify
94
-
95
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
96
- except Exception: # noqa: BLE001
97
- return False
98
 
99
 
100
  def _is_clean_number(s: str) -> bool:
101
- """True iff the whole string IS a single number (allowing a leading/trailing
102
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
103
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
104
- the numeric tier must not fire on it (its `_to_float` would grab the leading
105
- '3' and false-positive-match any answer starting with 3)."""
106
  t = (s or "").strip().strip("%$").strip().replace(",", "")
107
  return bool(_NUMERIC_RE.fullmatch(t))
108
 
109
 
110
- def grade(
111
- gold: str,
112
- candidate: str,
113
- *,
114
- question: str = "",
115
- reward_mode: str = "",
116
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
117
- judge_model: str | None = None, # noqa: ARG001
118
- rel_tol: float = 1e-3,
119
- abs_tol: float = 1e-3,
120
- ) -> GradeResult:
121
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
124
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
125
- """
126
 
 
 
127
  if not gold or candidate is None:
128
  return GradeResult(0.0, "miss")
129
 
130
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
131
  if _normalize(gold) == _normalize(candidate):
132
  return GradeResult(1.0, "exact")
133
 
134
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
135
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
136
- # the leading number; those must go to exact/math_verify, which fail closed).
137
- if reward_mode == "numeric" or _is_clean_number(gold):
138
  g, c = _to_float(gold), _to_float(candidate)
139
  if g is not None and c is not None:
140
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
141
  return GradeResult(1.0, "numeric")
 
 
 
 
142
 
143
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
144
  if _math_verify_match(gold, candidate):
145
  return GradeResult(1.0, "math_verify")
146
 
147
  return GradeResult(0.0, "miss")
148
 
149
 
150
- def _tool_calls() -> int | None:
151
- """Number of agent tool calls this rollout, for the efficiency reward.
152
-
153
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
154
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
155
- (efficiency reward becomes null — the harness didn't report a count).
156
- """
157
  try:
158
  with open("/workdir/.n_tool_calls") as fh:
159
  return int(fh.read().strip())
@@ -168,24 +121,17 @@ def _tool_calls() -> int | None:
168
  return None
169
 
170
 
171
- def _tool_efficiency(n_calls: int | None) -> float | None:
172
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
173
-
174
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
175
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
176
- RL reward combiner decides gating/weights.
177
- """
178
- if n_calls is None:
179
  return None
180
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
181
  if budget <= 0:
182
  return None
183
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
184
 
185
 
186
- def _tols() -> tuple[float, float]:
187
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
188
- def _f(name: str) -> float:
189
  try:
190
  return float(os.environ.get(name, "") or 1e-3)
191
  except ValueError:
@@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]:
194
 
195
 
196
  def main_cli() -> int:
197
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
198
-
199
- Inputs (via env vars set by Harbor's [verifier.env]):
200
- EXPECTED_ANSWER — the gold
201
- QUESTION — the original question
202
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
203
-
204
- Predicted answer is read from stdin.
205
- Single float written to stdout. Exit code is always 0.
206
- """
207
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
208
  question = (os.environ.get("QUESTION") or "").strip()
209
  candidate = sys.stdin.read().strip()
210
  at, rt = _tols()
211
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
212
- print(f"{result.reward:.1f}")
213
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
214
- file=sys.stderr)
215
  return 0
216
 
217
 
218
  def main_json() -> int:
219
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
220
-
221
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
222
- correctness — 1.0 iff graded answer matches gold, else 0.0
223
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
224
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
225
-
226
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
227
- """
228
  import json
229
-
230
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
231
  question = (os.environ.get("QUESTION") or "").strip()
232
  candidate = sys.stdin.read().strip()
233
-
234
  if not candidate:
235
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
236
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
237
  return 0
238
-
239
  at, rt = _tols()
240
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
241
- n_calls = _tool_calls()
242
- eff = _tool_efficiency(n_calls)
243
- print(json.dumps({
244
- "correctness": float(result.reward),
245
- "submission": 1.0,
246
- "tool_efficiency": eff,
247
- }))
248
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
249
- f"correctness={result.reward} method={result.method} "
250
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
251
  return 0
252
 
253
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
 
 
 
 
 
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0013_081_13081725_qa_3/tests/grader.py CHANGED
@@ -1,42 +1,34 @@
1
- """Deterministic short-answer grader — NO LLM judge.
2
 
3
- Tiers (cheapest -> most expensive), all offline/deterministic:
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
- 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
- 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify)
7
-
8
- CLI form (used by tests/test.sh):
9
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
10
- -> reads predicted answer from stdin
11
- -> writes a single float ('1.0' or '0.0') to stdout
12
  """
13
-
14
  from __future__ import annotations
15
-
16
- import os
17
- import re
18
- import sys
19
  from dataclasses import dataclass
20
 
21
-
22
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
23
 
24
 
25
-
26
  @dataclass
27
  class GradeResult:
28
  reward: float
29
- method: str # "exact" | "numeric" | "llm" | "miss"
30
 
31
 
32
  def _normalize(s: str) -> str:
33
  return re.sub(r"\s+", " ", (s or "").strip().lower())
34
 
35
 
36
- def _to_float(s: str) -> float | None:
37
  if not s:
38
  return None
39
- m = _NUMERIC_RE.search(s.replace(",", ""))
40
  if not m:
41
  return None
42
  try:
@@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None:
45
  return None
46
 
47
 
48
- def _math_verify_match(gold: str, candidate: str) -> bool:
49
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
50
-
51
- Catches equivalences the naive float-parse misses: thousands separators,
52
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
53
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
54
- false positive). No network, no LLM.
55
- """
56
- try:
57
- from math_verify import parse, verify
58
-
59
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
60
- except Exception: # noqa: BLE001
61
- return False
62
 
63
 
64
  def _is_clean_number(s: str) -> bool:
65
- """True iff the whole string IS a single number (allowing a leading/trailing
66
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
67
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
68
- the numeric tier must not fire on it (its `_to_float` would grab the leading
69
- '3' and false-positive-match any answer starting with 3)."""
70
  t = (s or "").strip().strip("%$").strip().replace(",", "")
71
  return bool(_NUMERIC_RE.fullmatch(t))
72
 
73
 
74
- def grade(
75
- gold: str,
76
- candidate: str,
77
- *,
78
- question: str = "",
79
- reward_mode: str = "",
80
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
81
- judge_model: str | None = None, # noqa: ARG001
82
- rel_tol: float = 1e-3,
83
- abs_tol: float = 1e-3,
84
- ) -> GradeResult:
85
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
88
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
89
- """
90
 
 
 
91
  if not gold or candidate is None:
92
  return GradeResult(0.0, "miss")
93
 
94
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
95
  if _normalize(gold) == _normalize(candidate):
96
  return GradeResult(1.0, "exact")
97
 
98
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
99
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
100
- # the leading number; those must go to exact/math_verify, which fail closed).
101
- if reward_mode == "numeric" or _is_clean_number(gold):
102
  g, c = _to_float(gold), _to_float(candidate)
103
  if g is not None and c is not None:
104
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
105
  return GradeResult(1.0, "numeric")
 
 
 
 
106
 
107
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
108
  if _math_verify_match(gold, candidate):
109
  return GradeResult(1.0, "math_verify")
110
 
111
  return GradeResult(0.0, "miss")
112
 
113
 
114
- def _tool_calls() -> int | None:
115
- """Number of agent tool calls this rollout, for the efficiency reward.
116
-
117
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
118
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
119
- (efficiency reward becomes null — the harness didn't report a count).
120
- """
121
  try:
122
  with open("/workdir/.n_tool_calls") as fh:
123
  return int(fh.read().strip())
@@ -132,24 +121,17 @@ def _tool_calls() -> int | None:
132
  return None
133
 
134
 
135
- def _tool_efficiency(n_calls: int | None) -> float | None:
136
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
137
-
138
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
139
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
140
- RL reward combiner decides gating/weights.
141
- """
142
- if n_calls is None:
143
  return None
144
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
145
  if budget <= 0:
146
  return None
147
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
148
 
149
 
150
- def _tols() -> tuple[float, float]:
151
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
152
- def _f(name: str) -> float:
153
  try:
154
  return float(os.environ.get(name, "") or 1e-3)
155
  except ValueError:
@@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]:
158
 
159
 
160
  def main_cli() -> int:
161
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
162
-
163
- Inputs (via env vars set by Harbor's [verifier.env]):
164
- EXPECTED_ANSWER — the gold
165
- QUESTION — the original question
166
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
167
-
168
- Predicted answer is read from stdin.
169
- Single float written to stdout. Exit code is always 0.
170
- """
171
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
172
  question = (os.environ.get("QUESTION") or "").strip()
173
  candidate = sys.stdin.read().strip()
174
  at, rt = _tols()
175
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
176
- print(f"{result.reward:.1f}")
177
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
178
- file=sys.stderr)
179
  return 0
180
 
181
 
182
  def main_json() -> int:
183
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
184
-
185
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
186
- correctness — 1.0 iff graded answer matches gold, else 0.0
187
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
188
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
189
-
190
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
191
- """
192
  import json
193
-
194
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
195
  question = (os.environ.get("QUESTION") or "").strip()
196
  candidate = sys.stdin.read().strip()
197
-
198
  if not candidate:
199
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
200
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
201
  return 0
202
-
203
  at, rt = _tols()
204
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
205
- n_calls = _tool_calls()
206
- eff = _tool_efficiency(n_calls)
207
- print(json.dumps({
208
- "correctness": float(result.reward),
209
- "submission": 1.0,
210
- "tool_efficiency": eff,
211
- }))
212
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
213
- f"correctness={result.reward} method={result.method} "
214
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
215
  return 0
216
 
217
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
17
 
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0013_604_13604091_qa_2/tests/grader.py CHANGED
@@ -1,78 +1,34 @@
1
- """Shared three-tier grader.
2
 
3
- Used by both runtimes:
4
- * `env/server.py` — inline inside the `final_answer` ORS @tool method
5
- * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py
6
- and invoked with `python3 /tests/grader.py < /workdir/answer.txt`
7
-
8
- Tiers (cheapest → most expensive):
9
  1. Exact (case-insensitive, whitespace-collapsed)
10
- 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3)
11
- 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt)
12
- — only invoked if OPENAI_API_KEY is set
13
-
14
- CLI form (used by tests/test.sh):
15
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
16
- → reads predicted answer from stdin
17
- → writes a single float ('1.0' or '0.0') to stdout
18
- → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt
19
  """
20
-
21
  from __future__ import annotations
22
-
23
- import os
24
- import re
25
- import sys
26
  from dataclasses import dataclass
27
 
28
-
29
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
30
 
31
- # Locked in PLAN.md §"Locked decisions" — adapted from
32
- # https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py
33
- JUDGE_PROMPT = """You are grading short answers from a data-science agent.
34
- Decide whether the predicted answer is semantically equivalent to the gold answer.
35
-
36
- Rules:
37
- - Case, punctuation, whitespace, articles ("the"), and trailing units don't matter.
38
- - For numbers: predicted must match to the last significant figure of the gold
39
- (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT).
40
- - Extra surrounding prose is fine if the gold value is clearly stated
41
- (gold "5", predicted "There are 5 distinct categories" -> CORRECT).
42
- - Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT).
43
- - Parenthetical annotations in the gold are equivalence hints, not required
44
- (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT;
45
- gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT).
46
- - Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X%
47
- is CORRECT as long as the core numeric value matches
48
- (gold "21.334% in 2014", predicted "21.334" -> CORRECT;
49
- gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch).
50
- - Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one
51
- thing (e.g. "which model?"), predicting either listed value is CORRECT.
52
- - If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED.
53
- - If it commits to a different value -> INCORRECT.
54
-
55
- Question: {question}
56
- Gold answer: {gold}
57
- Predicted answer: {pred}
58
-
59
- Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED)."""
60
-
61
 
62
  @dataclass
63
  class GradeResult:
64
  reward: float
65
- method: str # "exact" | "numeric" | "llm" | "miss"
66
 
67
 
68
  def _normalize(s: str) -> str:
69
  return re.sub(r"\s+", " ", (s or "").strip().lower())
70
 
71
 
72
- def _to_float(s: str) -> float | None:
73
  if not s:
74
  return None
75
- m = _NUMERIC_RE.search(s.replace(",", ""))
76
  if not m:
77
  return None
78
  try:
@@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None:
81
  return None
82
 
83
 
84
- def _math_verify_match(gold: str, candidate: str) -> bool:
85
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
86
-
87
- Catches equivalences the naive float-parse misses: thousands separators,
88
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
89
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
90
- false positive). No network, no LLM.
91
- """
92
- try:
93
- from math_verify import parse, verify
94
-
95
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
96
- except Exception: # noqa: BLE001
97
- return False
98
 
99
 
100
  def _is_clean_number(s: str) -> bool:
101
- """True iff the whole string IS a single number (allowing a leading/trailing
102
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
103
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
104
- the numeric tier must not fire on it (its `_to_float` would grab the leading
105
- '3' and false-positive-match any answer starting with 3)."""
106
  t = (s or "").strip().strip("%$").strip().replace(",", "")
107
  return bool(_NUMERIC_RE.fullmatch(t))
108
 
109
 
110
- def grade(
111
- gold: str,
112
- candidate: str,
113
- *,
114
- question: str = "",
115
- reward_mode: str = "",
116
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
117
- judge_model: str | None = None, # noqa: ARG001
118
- rel_tol: float = 1e-3,
119
- abs_tol: float = 1e-3,
120
- ) -> GradeResult:
121
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
124
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
125
- """
126
 
 
 
127
  if not gold or candidate is None:
128
  return GradeResult(0.0, "miss")
129
 
130
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
131
  if _normalize(gold) == _normalize(candidate):
132
  return GradeResult(1.0, "exact")
133
 
134
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
135
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
136
- # the leading number; those must go to exact/math_verify, which fail closed).
137
- if reward_mode == "numeric" or _is_clean_number(gold):
138
  g, c = _to_float(gold), _to_float(candidate)
139
  if g is not None and c is not None:
140
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
141
  return GradeResult(1.0, "numeric")
 
 
 
 
142
 
143
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
144
  if _math_verify_match(gold, candidate):
145
  return GradeResult(1.0, "math_verify")
146
 
147
  return GradeResult(0.0, "miss")
148
 
149
 
150
- def _tool_calls() -> int | None:
151
- """Number of agent tool calls this rollout, for the efficiency reward.
152
-
153
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
154
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
155
- (efficiency reward becomes null — the harness didn't report a count).
156
- """
157
  try:
158
  with open("/workdir/.n_tool_calls") as fh:
159
  return int(fh.read().strip())
@@ -168,24 +121,17 @@ def _tool_calls() -> int | None:
168
  return None
169
 
170
 
171
- def _tool_efficiency(n_calls: int | None) -> float | None:
172
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
173
-
174
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
175
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
176
- RL reward combiner decides gating/weights.
177
- """
178
- if n_calls is None:
179
  return None
180
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
181
  if budget <= 0:
182
  return None
183
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
184
 
185
 
186
- def _tols() -> tuple[float, float]:
187
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
188
- def _f(name: str) -> float:
189
  try:
190
  return float(os.environ.get(name, "") or 1e-3)
191
  except ValueError:
@@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]:
194
 
195
 
196
  def main_cli() -> int:
197
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
198
-
199
- Inputs (via env vars set by Harbor's [verifier.env]):
200
- EXPECTED_ANSWER — the gold
201
- QUESTION — the original question
202
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
203
-
204
- Predicted answer is read from stdin.
205
- Single float written to stdout. Exit code is always 0.
206
- """
207
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
208
  question = (os.environ.get("QUESTION") or "").strip()
209
  candidate = sys.stdin.read().strip()
210
  at, rt = _tols()
211
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
212
- print(f"{result.reward:.1f}")
213
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
214
- file=sys.stderr)
215
  return 0
216
 
217
 
218
  def main_json() -> int:
219
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
220
-
221
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
222
- correctness — 1.0 iff graded answer matches gold, else 0.0
223
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
224
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
225
-
226
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
227
- """
228
  import json
229
-
230
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
231
  question = (os.environ.get("QUESTION") or "").strip()
232
  candidate = sys.stdin.read().strip()
233
-
234
  if not candidate:
235
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
236
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
237
  return 0
238
-
239
  at, rt = _tols()
240
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
241
- n_calls = _tool_calls()
242
- eff = _tool_efficiency(n_calls)
243
- print(json.dumps({
244
- "correctness": float(result.reward),
245
- "submission": 1.0,
246
- "tool_efficiency": eff,
247
- }))
248
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
249
- f"correctness={result.reward} method={result.method} "
250
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
251
  return 0
252
 
253
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
 
 
 
 
 
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0013_733_13733964_qa_1/tests/grader.py CHANGED
@@ -1,78 +1,34 @@
1
- """Shared three-tier grader.
2
 
3
- Used by both runtimes:
4
- * `env/server.py` — inline inside the `final_answer` ORS @tool method
5
- * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py
6
- and invoked with `python3 /tests/grader.py < /workdir/answer.txt`
7
-
8
- Tiers (cheapest → most expensive):
9
  1. Exact (case-insensitive, whitespace-collapsed)
10
- 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3)
11
- 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt)
12
- — only invoked if OPENAI_API_KEY is set
13
-
14
- CLI form (used by tests/test.sh):
15
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
16
- → reads predicted answer from stdin
17
- → writes a single float ('1.0' or '0.0') to stdout
18
- → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt
19
  """
20
-
21
  from __future__ import annotations
22
-
23
- import os
24
- import re
25
- import sys
26
  from dataclasses import dataclass
27
 
28
-
29
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
30
 
31
- # Locked in PLAN.md §"Locked decisions" — adapted from
32
- # https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py
33
- JUDGE_PROMPT = """You are grading short answers from a data-science agent.
34
- Decide whether the predicted answer is semantically equivalent to the gold answer.
35
-
36
- Rules:
37
- - Case, punctuation, whitespace, articles ("the"), and trailing units don't matter.
38
- - For numbers: predicted must match to the last significant figure of the gold
39
- (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT).
40
- - Extra surrounding prose is fine if the gold value is clearly stated
41
- (gold "5", predicted "There are 5 distinct categories" -> CORRECT).
42
- - Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT).
43
- - Parenthetical annotations in the gold are equivalence hints, not required
44
- (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT;
45
- gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT).
46
- - Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X%
47
- is CORRECT as long as the core numeric value matches
48
- (gold "21.334% in 2014", predicted "21.334" -> CORRECT;
49
- gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch).
50
- - Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one
51
- thing (e.g. "which model?"), predicting either listed value is CORRECT.
52
- - If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED.
53
- - If it commits to a different value -> INCORRECT.
54
-
55
- Question: {question}
56
- Gold answer: {gold}
57
- Predicted answer: {pred}
58
-
59
- Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED)."""
60
-
61
 
62
  @dataclass
63
  class GradeResult:
64
  reward: float
65
- method: str # "exact" | "numeric" | "llm" | "miss"
66
 
67
 
68
  def _normalize(s: str) -> str:
69
  return re.sub(r"\s+", " ", (s or "").strip().lower())
70
 
71
 
72
- def _to_float(s: str) -> float | None:
73
  if not s:
74
  return None
75
- m = _NUMERIC_RE.search(s.replace(",", ""))
76
  if not m:
77
  return None
78
  try:
@@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None:
81
  return None
82
 
83
 
84
- def _math_verify_match(gold: str, candidate: str) -> bool:
85
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
86
-
87
- Catches equivalences the naive float-parse misses: thousands separators,
88
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
89
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
90
- false positive). No network, no LLM.
91
- """
92
- try:
93
- from math_verify import parse, verify
94
-
95
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
96
- except Exception: # noqa: BLE001
97
- return False
98
 
99
 
100
  def _is_clean_number(s: str) -> bool:
101
- """True iff the whole string IS a single number (allowing a leading/trailing
102
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
103
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
104
- the numeric tier must not fire on it (its `_to_float` would grab the leading
105
- '3' and false-positive-match any answer starting with 3)."""
106
  t = (s or "").strip().strip("%$").strip().replace(",", "")
107
  return bool(_NUMERIC_RE.fullmatch(t))
108
 
109
 
110
- def grade(
111
- gold: str,
112
- candidate: str,
113
- *,
114
- question: str = "",
115
- reward_mode: str = "",
116
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
117
- judge_model: str | None = None, # noqa: ARG001
118
- rel_tol: float = 1e-3,
119
- abs_tol: float = 1e-3,
120
- ) -> GradeResult:
121
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
124
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
125
- """
126
 
 
 
127
  if not gold or candidate is None:
128
  return GradeResult(0.0, "miss")
129
 
130
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
131
  if _normalize(gold) == _normalize(candidate):
132
  return GradeResult(1.0, "exact")
133
 
134
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
135
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
136
- # the leading number; those must go to exact/math_verify, which fail closed).
137
- if reward_mode == "numeric" or _is_clean_number(gold):
138
  g, c = _to_float(gold), _to_float(candidate)
139
  if g is not None and c is not None:
140
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
141
  return GradeResult(1.0, "numeric")
 
 
 
 
142
 
143
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
144
  if _math_verify_match(gold, candidate):
145
  return GradeResult(1.0, "math_verify")
146
 
147
  return GradeResult(0.0, "miss")
148
 
149
 
150
- def _tool_calls() -> int | None:
151
- """Number of agent tool calls this rollout, for the efficiency reward.
152
-
153
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
154
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
155
- (efficiency reward becomes null — the harness didn't report a count).
156
- """
157
  try:
158
  with open("/workdir/.n_tool_calls") as fh:
159
  return int(fh.read().strip())
@@ -168,24 +121,17 @@ def _tool_calls() -> int | None:
168
  return None
169
 
170
 
171
- def _tool_efficiency(n_calls: int | None) -> float | None:
172
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
173
-
174
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
175
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
176
- RL reward combiner decides gating/weights.
177
- """
178
- if n_calls is None:
179
  return None
180
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
181
  if budget <= 0:
182
  return None
183
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
184
 
185
 
186
- def _tols() -> tuple[float, float]:
187
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
188
- def _f(name: str) -> float:
189
  try:
190
  return float(os.environ.get(name, "") or 1e-3)
191
  except ValueError:
@@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]:
194
 
195
 
196
  def main_cli() -> int:
197
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
198
-
199
- Inputs (via env vars set by Harbor's [verifier.env]):
200
- EXPECTED_ANSWER — the gold
201
- QUESTION — the original question
202
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
203
-
204
- Predicted answer is read from stdin.
205
- Single float written to stdout. Exit code is always 0.
206
- """
207
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
208
  question = (os.environ.get("QUESTION") or "").strip()
209
  candidate = sys.stdin.read().strip()
210
  at, rt = _tols()
211
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
212
- print(f"{result.reward:.1f}")
213
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
214
- file=sys.stderr)
215
  return 0
216
 
217
 
218
  def main_json() -> int:
219
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
220
-
221
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
222
- correctness — 1.0 iff graded answer matches gold, else 0.0
223
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
224
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
225
-
226
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
227
- """
228
  import json
229
-
230
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
231
  question = (os.environ.get("QUESTION") or "").strip()
232
  candidate = sys.stdin.read().strip()
233
-
234
  if not candidate:
235
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
236
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
237
  return 0
238
-
239
  at, rt = _tols()
240
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
241
- n_calls = _tool_calls()
242
- eff = _tool_efficiency(n_calls)
243
- print(json.dumps({
244
- "correctness": float(result.reward),
245
- "submission": 1.0,
246
- "tool_efficiency": eff,
247
- }))
248
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
249
- f"correctness={result.reward} method={result.method} "
250
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
251
  return 0
252
 
253
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
 
 
 
 
 
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0013_884_13884693_qa_1/tests/grader.py CHANGED
@@ -1,42 +1,34 @@
1
- """Deterministic short-answer grader — NO LLM judge.
2
 
3
- Tiers (cheapest -> most expensive), all offline/deterministic:
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
- 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
- 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify)
7
-
8
- CLI form (used by tests/test.sh):
9
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
10
- -> reads predicted answer from stdin
11
- -> writes a single float ('1.0' or '0.0') to stdout
12
  """
13
-
14
  from __future__ import annotations
15
-
16
- import os
17
- import re
18
- import sys
19
  from dataclasses import dataclass
20
 
21
-
22
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
23
 
24
 
25
-
26
  @dataclass
27
  class GradeResult:
28
  reward: float
29
- method: str # "exact" | "numeric" | "llm" | "miss"
30
 
31
 
32
  def _normalize(s: str) -> str:
33
  return re.sub(r"\s+", " ", (s or "").strip().lower())
34
 
35
 
36
- def _to_float(s: str) -> float | None:
37
  if not s:
38
  return None
39
- m = _NUMERIC_RE.search(s.replace(",", ""))
40
  if not m:
41
  return None
42
  try:
@@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None:
45
  return None
46
 
47
 
48
- def _math_verify_match(gold: str, candidate: str) -> bool:
49
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
50
-
51
- Catches equivalences the naive float-parse misses: thousands separators,
52
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
53
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
54
- false positive). No network, no LLM.
55
- """
56
- try:
57
- from math_verify import parse, verify
58
-
59
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
60
- except Exception: # noqa: BLE001
61
- return False
62
 
63
 
64
  def _is_clean_number(s: str) -> bool:
65
- """True iff the whole string IS a single number (allowing a leading/trailing
66
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
67
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
68
- the numeric tier must not fire on it (its `_to_float` would grab the leading
69
- '3' and false-positive-match any answer starting with 3)."""
70
  t = (s or "").strip().strip("%$").strip().replace(",", "")
71
  return bool(_NUMERIC_RE.fullmatch(t))
72
 
73
 
74
- def grade(
75
- gold: str,
76
- candidate: str,
77
- *,
78
- question: str = "",
79
- reward_mode: str = "",
80
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
81
- judge_model: str | None = None, # noqa: ARG001
82
- rel_tol: float = 1e-3,
83
- abs_tol: float = 1e-3,
84
- ) -> GradeResult:
85
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
88
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
89
- """
90
 
 
 
91
  if not gold or candidate is None:
92
  return GradeResult(0.0, "miss")
93
 
94
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
95
  if _normalize(gold) == _normalize(candidate):
96
  return GradeResult(1.0, "exact")
97
 
98
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
99
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
100
- # the leading number; those must go to exact/math_verify, which fail closed).
101
- if reward_mode == "numeric" or _is_clean_number(gold):
102
  g, c = _to_float(gold), _to_float(candidate)
103
  if g is not None and c is not None:
104
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
105
  return GradeResult(1.0, "numeric")
 
 
 
 
106
 
107
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
108
  if _math_verify_match(gold, candidate):
109
  return GradeResult(1.0, "math_verify")
110
 
111
  return GradeResult(0.0, "miss")
112
 
113
 
114
- def _tool_calls() -> int | None:
115
- """Number of agent tool calls this rollout, for the efficiency reward.
116
-
117
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
118
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
119
- (efficiency reward becomes null — the harness didn't report a count).
120
- """
121
  try:
122
  with open("/workdir/.n_tool_calls") as fh:
123
  return int(fh.read().strip())
@@ -132,24 +121,17 @@ def _tool_calls() -> int | None:
132
  return None
133
 
134
 
135
- def _tool_efficiency(n_calls: int | None) -> float | None:
136
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
137
-
138
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
139
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
140
- RL reward combiner decides gating/weights.
141
- """
142
- if n_calls is None:
143
  return None
144
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
145
  if budget <= 0:
146
  return None
147
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
148
 
149
 
150
- def _tols() -> tuple[float, float]:
151
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
152
- def _f(name: str) -> float:
153
  try:
154
  return float(os.environ.get(name, "") or 1e-3)
155
  except ValueError:
@@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]:
158
 
159
 
160
  def main_cli() -> int:
161
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
162
-
163
- Inputs (via env vars set by Harbor's [verifier.env]):
164
- EXPECTED_ANSWER — the gold
165
- QUESTION — the original question
166
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
167
-
168
- Predicted answer is read from stdin.
169
- Single float written to stdout. Exit code is always 0.
170
- """
171
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
172
  question = (os.environ.get("QUESTION") or "").strip()
173
  candidate = sys.stdin.read().strip()
174
  at, rt = _tols()
175
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
176
- print(f"{result.reward:.1f}")
177
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
178
- file=sys.stderr)
179
  return 0
180
 
181
 
182
  def main_json() -> int:
183
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
184
-
185
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
186
- correctness — 1.0 iff graded answer matches gold, else 0.0
187
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
188
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
189
-
190
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
191
- """
192
  import json
193
-
194
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
195
  question = (os.environ.get("QUESTION") or "").strip()
196
  candidate = sys.stdin.read().strip()
197
-
198
  if not candidate:
199
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
200
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
201
  return 0
202
-
203
  at, rt = _tols()
204
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
205
- n_calls = _tool_calls()
206
- eff = _tool_efficiency(n_calls)
207
- print(json.dumps({
208
- "correctness": float(result.reward),
209
- "submission": 1.0,
210
- "tool_efficiency": eff,
211
- }))
212
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
213
- f"correctness={result.reward} method={result.method} "
214
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
215
  return 0
216
 
217
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
17
 
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0013_911_13911248_qa_1/tests/grader.py CHANGED
@@ -1,42 +1,34 @@
1
- """Deterministic short-answer grader — NO LLM judge.
2
 
3
- Tiers (cheapest -> most expensive), all offline/deterministic:
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
- 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
- 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify)
7
-
8
- CLI form (used by tests/test.sh):
9
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
10
- -> reads predicted answer from stdin
11
- -> writes a single float ('1.0' or '0.0') to stdout
12
  """
13
-
14
  from __future__ import annotations
15
-
16
- import os
17
- import re
18
- import sys
19
  from dataclasses import dataclass
20
 
21
-
22
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
23
 
24
 
25
-
26
  @dataclass
27
  class GradeResult:
28
  reward: float
29
- method: str # "exact" | "numeric" | "llm" | "miss"
30
 
31
 
32
  def _normalize(s: str) -> str:
33
  return re.sub(r"\s+", " ", (s or "").strip().lower())
34
 
35
 
36
- def _to_float(s: str) -> float | None:
37
  if not s:
38
  return None
39
- m = _NUMERIC_RE.search(s.replace(",", ""))
40
  if not m:
41
  return None
42
  try:
@@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None:
45
  return None
46
 
47
 
48
- def _math_verify_match(gold: str, candidate: str) -> bool:
49
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
50
-
51
- Catches equivalences the naive float-parse misses: thousands separators,
52
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
53
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
54
- false positive). No network, no LLM.
55
- """
56
- try:
57
- from math_verify import parse, verify
58
-
59
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
60
- except Exception: # noqa: BLE001
61
- return False
62
 
63
 
64
  def _is_clean_number(s: str) -> bool:
65
- """True iff the whole string IS a single number (allowing a leading/trailing
66
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
67
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
68
- the numeric tier must not fire on it (its `_to_float` would grab the leading
69
- '3' and false-positive-match any answer starting with 3)."""
70
  t = (s or "").strip().strip("%$").strip().replace(",", "")
71
  return bool(_NUMERIC_RE.fullmatch(t))
72
 
73
 
74
- def grade(
75
- gold: str,
76
- candidate: str,
77
- *,
78
- question: str = "",
79
- reward_mode: str = "",
80
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
81
- judge_model: str | None = None, # noqa: ARG001
82
- rel_tol: float = 1e-3,
83
- abs_tol: float = 1e-3,
84
- ) -> GradeResult:
85
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
88
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
89
- """
90
 
 
 
91
  if not gold or candidate is None:
92
  return GradeResult(0.0, "miss")
93
 
94
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
95
  if _normalize(gold) == _normalize(candidate):
96
  return GradeResult(1.0, "exact")
97
 
98
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
99
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
100
- # the leading number; those must go to exact/math_verify, which fail closed).
101
- if reward_mode == "numeric" or _is_clean_number(gold):
102
  g, c = _to_float(gold), _to_float(candidate)
103
  if g is not None and c is not None:
104
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
105
  return GradeResult(1.0, "numeric")
 
 
 
 
106
 
107
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
108
  if _math_verify_match(gold, candidate):
109
  return GradeResult(1.0, "math_verify")
110
 
111
  return GradeResult(0.0, "miss")
112
 
113
 
114
- def _tool_calls() -> int | None:
115
- """Number of agent tool calls this rollout, for the efficiency reward.
116
-
117
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
118
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
119
- (efficiency reward becomes null — the harness didn't report a count).
120
- """
121
  try:
122
  with open("/workdir/.n_tool_calls") as fh:
123
  return int(fh.read().strip())
@@ -132,24 +121,17 @@ def _tool_calls() -> int | None:
132
  return None
133
 
134
 
135
- def _tool_efficiency(n_calls: int | None) -> float | None:
136
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
137
-
138
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
139
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
140
- RL reward combiner decides gating/weights.
141
- """
142
- if n_calls is None:
143
  return None
144
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
145
  if budget <= 0:
146
  return None
147
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
148
 
149
 
150
- def _tols() -> tuple[float, float]:
151
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
152
- def _f(name: str) -> float:
153
  try:
154
  return float(os.environ.get(name, "") or 1e-3)
155
  except ValueError:
@@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]:
158
 
159
 
160
  def main_cli() -> int:
161
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
162
-
163
- Inputs (via env vars set by Harbor's [verifier.env]):
164
- EXPECTED_ANSWER — the gold
165
- QUESTION — the original question
166
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
167
-
168
- Predicted answer is read from stdin.
169
- Single float written to stdout. Exit code is always 0.
170
- """
171
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
172
  question = (os.environ.get("QUESTION") or "").strip()
173
  candidate = sys.stdin.read().strip()
174
  at, rt = _tols()
175
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
176
- print(f"{result.reward:.1f}")
177
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
178
- file=sys.stderr)
179
  return 0
180
 
181
 
182
  def main_json() -> int:
183
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
184
-
185
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
186
- correctness — 1.0 iff graded answer matches gold, else 0.0
187
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
188
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
189
-
190
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
191
- """
192
  import json
193
-
194
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
195
  question = (os.environ.get("QUESTION") or "").strip()
196
  candidate = sys.stdin.read().strip()
197
-
198
  if not candidate:
199
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
200
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
201
  return 0
202
-
203
  at, rt = _tols()
204
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
205
- n_calls = _tool_calls()
206
- eff = _tool_efficiency(n_calls)
207
- print(json.dumps({
208
- "correctness": float(result.reward),
209
- "submission": 1.0,
210
- "tool_efficiency": eff,
211
- }))
212
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
213
- f"correctness={result.reward} method={result.method} "
214
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
215
  return 0
216
 
217
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
17
 
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0014_089_14089673_qa_5/tests/grader.py CHANGED
@@ -1,42 +1,34 @@
1
- """Deterministic short-answer grader — NO LLM judge.
2
 
3
- Tiers (cheapest -> most expensive), all offline/deterministic:
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
- 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
- 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify)
7
-
8
- CLI form (used by tests/test.sh):
9
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
10
- -> reads predicted answer from stdin
11
- -> writes a single float ('1.0' or '0.0') to stdout
12
  """
13
-
14
  from __future__ import annotations
15
-
16
- import os
17
- import re
18
- import sys
19
  from dataclasses import dataclass
20
 
21
-
22
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
23
 
24
 
25
-
26
  @dataclass
27
  class GradeResult:
28
  reward: float
29
- method: str # "exact" | "numeric" | "llm" | "miss"
30
 
31
 
32
  def _normalize(s: str) -> str:
33
  return re.sub(r"\s+", " ", (s or "").strip().lower())
34
 
35
 
36
- def _to_float(s: str) -> float | None:
37
  if not s:
38
  return None
39
- m = _NUMERIC_RE.search(s.replace(",", ""))
40
  if not m:
41
  return None
42
  try:
@@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None:
45
  return None
46
 
47
 
48
- def _math_verify_match(gold: str, candidate: str) -> bool:
49
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
50
-
51
- Catches equivalences the naive float-parse misses: thousands separators,
52
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
53
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
54
- false positive). No network, no LLM.
55
- """
56
- try:
57
- from math_verify import parse, verify
58
-
59
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
60
- except Exception: # noqa: BLE001
61
- return False
62
 
63
 
64
  def _is_clean_number(s: str) -> bool:
65
- """True iff the whole string IS a single number (allowing a leading/trailing
66
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
67
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
68
- the numeric tier must not fire on it (its `_to_float` would grab the leading
69
- '3' and false-positive-match any answer starting with 3)."""
70
  t = (s or "").strip().strip("%$").strip().replace(",", "")
71
  return bool(_NUMERIC_RE.fullmatch(t))
72
 
73
 
74
- def grade(
75
- gold: str,
76
- candidate: str,
77
- *,
78
- question: str = "",
79
- reward_mode: str = "",
80
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
81
- judge_model: str | None = None, # noqa: ARG001
82
- rel_tol: float = 1e-3,
83
- abs_tol: float = 1e-3,
84
- ) -> GradeResult:
85
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
88
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
89
- """
90
 
 
 
91
  if not gold or candidate is None:
92
  return GradeResult(0.0, "miss")
93
 
94
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
95
  if _normalize(gold) == _normalize(candidate):
96
  return GradeResult(1.0, "exact")
97
 
98
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
99
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
100
- # the leading number; those must go to exact/math_verify, which fail closed).
101
- if reward_mode == "numeric" or _is_clean_number(gold):
102
  g, c = _to_float(gold), _to_float(candidate)
103
  if g is not None and c is not None:
104
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
105
  return GradeResult(1.0, "numeric")
 
 
 
 
106
 
107
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
108
  if _math_verify_match(gold, candidate):
109
  return GradeResult(1.0, "math_verify")
110
 
111
  return GradeResult(0.0, "miss")
112
 
113
 
114
- def _tool_calls() -> int | None:
115
- """Number of agent tool calls this rollout, for the efficiency reward.
116
-
117
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
118
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
119
- (efficiency reward becomes null — the harness didn't report a count).
120
- """
121
  try:
122
  with open("/workdir/.n_tool_calls") as fh:
123
  return int(fh.read().strip())
@@ -132,24 +121,17 @@ def _tool_calls() -> int | None:
132
  return None
133
 
134
 
135
- def _tool_efficiency(n_calls: int | None) -> float | None:
136
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
137
-
138
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
139
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
140
- RL reward combiner decides gating/weights.
141
- """
142
- if n_calls is None:
143
  return None
144
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
145
  if budget <= 0:
146
  return None
147
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
148
 
149
 
150
- def _tols() -> tuple[float, float]:
151
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
152
- def _f(name: str) -> float:
153
  try:
154
  return float(os.environ.get(name, "") or 1e-3)
155
  except ValueError:
@@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]:
158
 
159
 
160
  def main_cli() -> int:
161
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
162
-
163
- Inputs (via env vars set by Harbor's [verifier.env]):
164
- EXPECTED_ANSWER — the gold
165
- QUESTION — the original question
166
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
167
-
168
- Predicted answer is read from stdin.
169
- Single float written to stdout. Exit code is always 0.
170
- """
171
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
172
  question = (os.environ.get("QUESTION") or "").strip()
173
  candidate = sys.stdin.read().strip()
174
  at, rt = _tols()
175
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
176
- print(f"{result.reward:.1f}")
177
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
178
- file=sys.stderr)
179
  return 0
180
 
181
 
182
  def main_json() -> int:
183
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
184
-
185
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
186
- correctness — 1.0 iff graded answer matches gold, else 0.0
187
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
188
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
189
-
190
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
191
- """
192
  import json
193
-
194
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
195
  question = (os.environ.get("QUESTION") or "").strip()
196
  candidate = sys.stdin.read().strip()
197
-
198
  if not candidate:
199
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
200
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
201
  return 0
202
-
203
  at, rt = _tols()
204
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
205
- n_calls = _tool_calls()
206
- eff = _tool_efficiency(n_calls)
207
- print(json.dumps({
208
- "correctness": float(result.reward),
209
- "submission": 1.0,
210
- "tool_efficiency": eff,
211
- }))
212
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
213
- f"correctness={result.reward} method={result.method} "
214
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
215
  return 0
216
 
217
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
17
 
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0014_469_14469283_qa_3/tests/grader.py CHANGED
@@ -1,78 +1,34 @@
1
- """Shared three-tier grader.
2
 
3
- Used by both runtimes:
4
- * `env/server.py` — inline inside the `final_answer` ORS @tool method
5
- * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py
6
- and invoked with `python3 /tests/grader.py < /workdir/answer.txt`
7
-
8
- Tiers (cheapest → most expensive):
9
  1. Exact (case-insensitive, whitespace-collapsed)
10
- 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3)
11
- 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt)
12
- — only invoked if OPENAI_API_KEY is set
13
-
14
- CLI form (used by tests/test.sh):
15
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
16
- → reads predicted answer from stdin
17
- → writes a single float ('1.0' or '0.0') to stdout
18
- → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt
19
  """
20
-
21
  from __future__ import annotations
22
-
23
- import os
24
- import re
25
- import sys
26
  from dataclasses import dataclass
27
 
28
-
29
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
30
 
31
- # Locked in PLAN.md §"Locked decisions" — adapted from
32
- # https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py
33
- JUDGE_PROMPT = """You are grading short answers from a data-science agent.
34
- Decide whether the predicted answer is semantically equivalent to the gold answer.
35
-
36
- Rules:
37
- - Case, punctuation, whitespace, articles ("the"), and trailing units don't matter.
38
- - For numbers: predicted must match to the last significant figure of the gold
39
- (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT).
40
- - Extra surrounding prose is fine if the gold value is clearly stated
41
- (gold "5", predicted "There are 5 distinct categories" -> CORRECT).
42
- - Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT).
43
- - Parenthetical annotations in the gold are equivalence hints, not required
44
- (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT;
45
- gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT).
46
- - Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X%
47
- is CORRECT as long as the core numeric value matches
48
- (gold "21.334% in 2014", predicted "21.334" -> CORRECT;
49
- gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch).
50
- - Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one
51
- thing (e.g. "which model?"), predicting either listed value is CORRECT.
52
- - If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED.
53
- - If it commits to a different value -> INCORRECT.
54
-
55
- Question: {question}
56
- Gold answer: {gold}
57
- Predicted answer: {pred}
58
-
59
- Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED)."""
60
-
61
 
62
  @dataclass
63
  class GradeResult:
64
  reward: float
65
- method: str # "exact" | "numeric" | "llm" | "miss"
66
 
67
 
68
  def _normalize(s: str) -> str:
69
  return re.sub(r"\s+", " ", (s or "").strip().lower())
70
 
71
 
72
- def _to_float(s: str) -> float | None:
73
  if not s:
74
  return None
75
- m = _NUMERIC_RE.search(s.replace(",", ""))
76
  if not m:
77
  return None
78
  try:
@@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None:
81
  return None
82
 
83
 
84
- def _math_verify_match(gold: str, candidate: str) -> bool:
85
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
86
-
87
- Catches equivalences the naive float-parse misses: thousands separators,
88
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
89
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
90
- false positive). No network, no LLM.
91
- """
92
- try:
93
- from math_verify import parse, verify
94
-
95
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
96
- except Exception: # noqa: BLE001
97
- return False
98
 
99
 
100
  def _is_clean_number(s: str) -> bool:
101
- """True iff the whole string IS a single number (allowing a leading/trailing
102
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
103
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
104
- the numeric tier must not fire on it (its `_to_float` would grab the leading
105
- '3' and false-positive-match any answer starting with 3)."""
106
  t = (s or "").strip().strip("%$").strip().replace(",", "")
107
  return bool(_NUMERIC_RE.fullmatch(t))
108
 
109
 
110
- def grade(
111
- gold: str,
112
- candidate: str,
113
- *,
114
- question: str = "",
115
- reward_mode: str = "",
116
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
117
- judge_model: str | None = None, # noqa: ARG001
118
- rel_tol: float = 1e-3,
119
- abs_tol: float = 1e-3,
120
- ) -> GradeResult:
121
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
124
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
125
- """
126
 
 
 
127
  if not gold or candidate is None:
128
  return GradeResult(0.0, "miss")
129
 
130
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
131
  if _normalize(gold) == _normalize(candidate):
132
  return GradeResult(1.0, "exact")
133
 
134
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
135
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
136
- # the leading number; those must go to exact/math_verify, which fail closed).
137
- if reward_mode == "numeric" or _is_clean_number(gold):
138
  g, c = _to_float(gold), _to_float(candidate)
139
  if g is not None and c is not None:
140
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
141
  return GradeResult(1.0, "numeric")
 
 
 
 
142
 
143
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
144
  if _math_verify_match(gold, candidate):
145
  return GradeResult(1.0, "math_verify")
146
 
147
  return GradeResult(0.0, "miss")
148
 
149
 
150
- def _tool_calls() -> int | None:
151
- """Number of agent tool calls this rollout, for the efficiency reward.
152
-
153
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
154
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
155
- (efficiency reward becomes null — the harness didn't report a count).
156
- """
157
  try:
158
  with open("/workdir/.n_tool_calls") as fh:
159
  return int(fh.read().strip())
@@ -168,24 +121,17 @@ def _tool_calls() -> int | None:
168
  return None
169
 
170
 
171
- def _tool_efficiency(n_calls: int | None) -> float | None:
172
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
173
-
174
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
175
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
176
- RL reward combiner decides gating/weights.
177
- """
178
- if n_calls is None:
179
  return None
180
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
181
  if budget <= 0:
182
  return None
183
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
184
 
185
 
186
- def _tols() -> tuple[float, float]:
187
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
188
- def _f(name: str) -> float:
189
  try:
190
  return float(os.environ.get(name, "") or 1e-3)
191
  except ValueError:
@@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]:
194
 
195
 
196
  def main_cli() -> int:
197
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
198
-
199
- Inputs (via env vars set by Harbor's [verifier.env]):
200
- EXPECTED_ANSWER — the gold
201
- QUESTION — the original question
202
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
203
-
204
- Predicted answer is read from stdin.
205
- Single float written to stdout. Exit code is always 0.
206
- """
207
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
208
  question = (os.environ.get("QUESTION") or "").strip()
209
  candidate = sys.stdin.read().strip()
210
  at, rt = _tols()
211
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
212
- print(f"{result.reward:.1f}")
213
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
214
- file=sys.stderr)
215
  return 0
216
 
217
 
218
  def main_json() -> int:
219
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
220
-
221
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
222
- correctness — 1.0 iff graded answer matches gold, else 0.0
223
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
224
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
225
-
226
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
227
- """
228
  import json
229
-
230
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
231
  question = (os.environ.get("QUESTION") or "").strip()
232
  candidate = sys.stdin.read().strip()
233
-
234
  if not candidate:
235
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
236
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
237
  return 0
238
-
239
  at, rt = _tols()
240
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
241
- n_calls = _tool_calls()
242
- eff = _tool_efficiency(n_calls)
243
- print(json.dumps({
244
- "correctness": float(result.reward),
245
- "submission": 1.0,
246
- "tool_efficiency": eff,
247
- }))
248
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
249
- f"correctness={result.reward} method={result.method} "
250
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
251
  return 0
252
 
253
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
 
 
 
 
 
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0014_469_14469283_qa_4/tests/grader.py CHANGED
@@ -1,78 +1,34 @@
1
- """Shared three-tier grader.
2
 
3
- Used by both runtimes:
4
- * `env/server.py` — inline inside the `final_answer` ORS @tool method
5
- * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py
6
- and invoked with `python3 /tests/grader.py < /workdir/answer.txt`
7
-
8
- Tiers (cheapest → most expensive):
9
  1. Exact (case-insensitive, whitespace-collapsed)
10
- 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3)
11
- 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt)
12
- — only invoked if OPENAI_API_KEY is set
13
-
14
- CLI form (used by tests/test.sh):
15
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
16
- → reads predicted answer from stdin
17
- → writes a single float ('1.0' or '0.0') to stdout
18
- → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt
19
  """
20
-
21
  from __future__ import annotations
22
-
23
- import os
24
- import re
25
- import sys
26
  from dataclasses import dataclass
27
 
28
-
29
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
30
 
31
- # Locked in PLAN.md §"Locked decisions" — adapted from
32
- # https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py
33
- JUDGE_PROMPT = """You are grading short answers from a data-science agent.
34
- Decide whether the predicted answer is semantically equivalent to the gold answer.
35
-
36
- Rules:
37
- - Case, punctuation, whitespace, articles ("the"), and trailing units don't matter.
38
- - For numbers: predicted must match to the last significant figure of the gold
39
- (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT).
40
- - Extra surrounding prose is fine if the gold value is clearly stated
41
- (gold "5", predicted "There are 5 distinct categories" -> CORRECT).
42
- - Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT).
43
- - Parenthetical annotations in the gold are equivalence hints, not required
44
- (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT;
45
- gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT).
46
- - Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X%
47
- is CORRECT as long as the core numeric value matches
48
- (gold "21.334% in 2014", predicted "21.334" -> CORRECT;
49
- gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch).
50
- - Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one
51
- thing (e.g. "which model?"), predicting either listed value is CORRECT.
52
- - If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED.
53
- - If it commits to a different value -> INCORRECT.
54
-
55
- Question: {question}
56
- Gold answer: {gold}
57
- Predicted answer: {pred}
58
-
59
- Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED)."""
60
-
61
 
62
  @dataclass
63
  class GradeResult:
64
  reward: float
65
- method: str # "exact" | "numeric" | "llm" | "miss"
66
 
67
 
68
  def _normalize(s: str) -> str:
69
  return re.sub(r"\s+", " ", (s or "").strip().lower())
70
 
71
 
72
- def _to_float(s: str) -> float | None:
73
  if not s:
74
  return None
75
- m = _NUMERIC_RE.search(s.replace(",", ""))
76
  if not m:
77
  return None
78
  try:
@@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None:
81
  return None
82
 
83
 
84
- def _math_verify_match(gold: str, candidate: str) -> bool:
85
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
86
-
87
- Catches equivalences the naive float-parse misses: thousands separators,
88
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
89
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
90
- false positive). No network, no LLM.
91
- """
92
- try:
93
- from math_verify import parse, verify
94
-
95
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
96
- except Exception: # noqa: BLE001
97
- return False
98
 
99
 
100
  def _is_clean_number(s: str) -> bool:
101
- """True iff the whole string IS a single number (allowing a leading/trailing
102
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
103
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
104
- the numeric tier must not fire on it (its `_to_float` would grab the leading
105
- '3' and false-positive-match any answer starting with 3)."""
106
  t = (s or "").strip().strip("%$").strip().replace(",", "")
107
  return bool(_NUMERIC_RE.fullmatch(t))
108
 
109
 
110
- def grade(
111
- gold: str,
112
- candidate: str,
113
- *,
114
- question: str = "",
115
- reward_mode: str = "",
116
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
117
- judge_model: str | None = None, # noqa: ARG001
118
- rel_tol: float = 1e-3,
119
- abs_tol: float = 1e-3,
120
- ) -> GradeResult:
121
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
124
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
125
- """
126
 
 
 
127
  if not gold or candidate is None:
128
  return GradeResult(0.0, "miss")
129
 
130
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
131
  if _normalize(gold) == _normalize(candidate):
132
  return GradeResult(1.0, "exact")
133
 
134
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
135
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
136
- # the leading number; those must go to exact/math_verify, which fail closed).
137
- if reward_mode == "numeric" or _is_clean_number(gold):
138
  g, c = _to_float(gold), _to_float(candidate)
139
  if g is not None and c is not None:
140
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
141
  return GradeResult(1.0, "numeric")
 
 
 
 
142
 
143
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
144
  if _math_verify_match(gold, candidate):
145
  return GradeResult(1.0, "math_verify")
146
 
147
  return GradeResult(0.0, "miss")
148
 
149
 
150
- def _tool_calls() -> int | None:
151
- """Number of agent tool calls this rollout, for the efficiency reward.
152
-
153
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
154
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
155
- (efficiency reward becomes null — the harness didn't report a count).
156
- """
157
  try:
158
  with open("/workdir/.n_tool_calls") as fh:
159
  return int(fh.read().strip())
@@ -168,24 +121,17 @@ def _tool_calls() -> int | None:
168
  return None
169
 
170
 
171
- def _tool_efficiency(n_calls: int | None) -> float | None:
172
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
173
-
174
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
175
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
176
- RL reward combiner decides gating/weights.
177
- """
178
- if n_calls is None:
179
  return None
180
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
181
  if budget <= 0:
182
  return None
183
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
184
 
185
 
186
- def _tols() -> tuple[float, float]:
187
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
188
- def _f(name: str) -> float:
189
  try:
190
  return float(os.environ.get(name, "") or 1e-3)
191
  except ValueError:
@@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]:
194
 
195
 
196
  def main_cli() -> int:
197
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
198
-
199
- Inputs (via env vars set by Harbor's [verifier.env]):
200
- EXPECTED_ANSWER — the gold
201
- QUESTION — the original question
202
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
203
-
204
- Predicted answer is read from stdin.
205
- Single float written to stdout. Exit code is always 0.
206
- """
207
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
208
  question = (os.environ.get("QUESTION") or "").strip()
209
  candidate = sys.stdin.read().strip()
210
  at, rt = _tols()
211
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
212
- print(f"{result.reward:.1f}")
213
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
214
- file=sys.stderr)
215
  return 0
216
 
217
 
218
  def main_json() -> int:
219
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
220
-
221
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
222
- correctness — 1.0 iff graded answer matches gold, else 0.0
223
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
224
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
225
-
226
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
227
- """
228
  import json
229
-
230
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
231
  question = (os.environ.get("QUESTION") or "").strip()
232
  candidate = sys.stdin.read().strip()
233
-
234
  if not candidate:
235
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
236
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
237
  return 0
238
-
239
  at, rt = _tols()
240
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
241
- n_calls = _tool_calls()
242
- eff = _tool_efficiency(n_calls)
243
- print(json.dumps({
244
- "correctness": float(result.reward),
245
- "submission": 1.0,
246
- "tool_efficiency": eff,
247
- }))
248
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
249
- f"correctness={result.reward} method={result.method} "
250
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
251
  return 0
252
 
253
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
 
 
 
 
 
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0014_933_14933483_qa_2/tests/grader.py CHANGED
@@ -1,78 +1,34 @@
1
- """Shared three-tier grader.
2
 
3
- Used by both runtimes:
4
- * `env/server.py` — inline inside the `final_answer` ORS @tool method
5
- * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py
6
- and invoked with `python3 /tests/grader.py < /workdir/answer.txt`
7
-
8
- Tiers (cheapest → most expensive):
9
  1. Exact (case-insensitive, whitespace-collapsed)
10
- 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3)
11
- 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt)
12
- — only invoked if OPENAI_API_KEY is set
13
-
14
- CLI form (used by tests/test.sh):
15
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
16
- → reads predicted answer from stdin
17
- → writes a single float ('1.0' or '0.0') to stdout
18
- → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt
19
  """
20
-
21
  from __future__ import annotations
22
-
23
- import os
24
- import re
25
- import sys
26
  from dataclasses import dataclass
27
 
28
-
29
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
30
 
31
- # Locked in PLAN.md §"Locked decisions" — adapted from
32
- # https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py
33
- JUDGE_PROMPT = """You are grading short answers from a data-science agent.
34
- Decide whether the predicted answer is semantically equivalent to the gold answer.
35
-
36
- Rules:
37
- - Case, punctuation, whitespace, articles ("the"), and trailing units don't matter.
38
- - For numbers: predicted must match to the last significant figure of the gold
39
- (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT).
40
- - Extra surrounding prose is fine if the gold value is clearly stated
41
- (gold "5", predicted "There are 5 distinct categories" -> CORRECT).
42
- - Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT).
43
- - Parenthetical annotations in the gold are equivalence hints, not required
44
- (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT;
45
- gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT).
46
- - Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X%
47
- is CORRECT as long as the core numeric value matches
48
- (gold "21.334% in 2014", predicted "21.334" -> CORRECT;
49
- gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch).
50
- - Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one
51
- thing (e.g. "which model?"), predicting either listed value is CORRECT.
52
- - If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED.
53
- - If it commits to a different value -> INCORRECT.
54
-
55
- Question: {question}
56
- Gold answer: {gold}
57
- Predicted answer: {pred}
58
-
59
- Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED)."""
60
-
61
 
62
  @dataclass
63
  class GradeResult:
64
  reward: float
65
- method: str # "exact" | "numeric" | "llm" | "miss"
66
 
67
 
68
  def _normalize(s: str) -> str:
69
  return re.sub(r"\s+", " ", (s or "").strip().lower())
70
 
71
 
72
- def _to_float(s: str) -> float | None:
73
  if not s:
74
  return None
75
- m = _NUMERIC_RE.search(s.replace(",", ""))
76
  if not m:
77
  return None
78
  try:
@@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None:
81
  return None
82
 
83
 
84
- def _math_verify_match(gold: str, candidate: str) -> bool:
85
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
86
-
87
- Catches equivalences the naive float-parse misses: thousands separators,
88
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
89
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
90
- false positive). No network, no LLM.
91
- """
92
- try:
93
- from math_verify import parse, verify
94
-
95
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
96
- except Exception: # noqa: BLE001
97
- return False
98
 
99
 
100
  def _is_clean_number(s: str) -> bool:
101
- """True iff the whole string IS a single number (allowing a leading/trailing
102
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
103
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
104
- the numeric tier must not fire on it (its `_to_float` would grab the leading
105
- '3' and false-positive-match any answer starting with 3)."""
106
  t = (s or "").strip().strip("%$").strip().replace(",", "")
107
  return bool(_NUMERIC_RE.fullmatch(t))
108
 
109
 
110
- def grade(
111
- gold: str,
112
- candidate: str,
113
- *,
114
- question: str = "",
115
- reward_mode: str = "",
116
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
117
- judge_model: str | None = None, # noqa: ARG001
118
- rel_tol: float = 1e-3,
119
- abs_tol: float = 1e-3,
120
- ) -> GradeResult:
121
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
124
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
125
- """
126
 
 
 
127
  if not gold or candidate is None:
128
  return GradeResult(0.0, "miss")
129
 
130
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
131
  if _normalize(gold) == _normalize(candidate):
132
  return GradeResult(1.0, "exact")
133
 
134
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
135
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
136
- # the leading number; those must go to exact/math_verify, which fail closed).
137
- if reward_mode == "numeric" or _is_clean_number(gold):
138
  g, c = _to_float(gold), _to_float(candidate)
139
  if g is not None and c is not None:
140
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
141
  return GradeResult(1.0, "numeric")
 
 
 
 
142
 
143
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
144
  if _math_verify_match(gold, candidate):
145
  return GradeResult(1.0, "math_verify")
146
 
147
  return GradeResult(0.0, "miss")
148
 
149
 
150
- def _tool_calls() -> int | None:
151
- """Number of agent tool calls this rollout, for the efficiency reward.
152
-
153
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
154
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
155
- (efficiency reward becomes null — the harness didn't report a count).
156
- """
157
  try:
158
  with open("/workdir/.n_tool_calls") as fh:
159
  return int(fh.read().strip())
@@ -168,24 +121,17 @@ def _tool_calls() -> int | None:
168
  return None
169
 
170
 
171
- def _tool_efficiency(n_calls: int | None) -> float | None:
172
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
173
-
174
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
175
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
176
- RL reward combiner decides gating/weights.
177
- """
178
- if n_calls is None:
179
  return None
180
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
181
  if budget <= 0:
182
  return None
183
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
184
 
185
 
186
- def _tols() -> tuple[float, float]:
187
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
188
- def _f(name: str) -> float:
189
  try:
190
  return float(os.environ.get(name, "") or 1e-3)
191
  except ValueError:
@@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]:
194
 
195
 
196
  def main_cli() -> int:
197
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
198
-
199
- Inputs (via env vars set by Harbor's [verifier.env]):
200
- EXPECTED_ANSWER — the gold
201
- QUESTION — the original question
202
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
203
-
204
- Predicted answer is read from stdin.
205
- Single float written to stdout. Exit code is always 0.
206
- """
207
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
208
  question = (os.environ.get("QUESTION") or "").strip()
209
  candidate = sys.stdin.read().strip()
210
  at, rt = _tols()
211
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
212
- print(f"{result.reward:.1f}")
213
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
214
- file=sys.stderr)
215
  return 0
216
 
217
 
218
  def main_json() -> int:
219
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
220
-
221
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
222
- correctness — 1.0 iff graded answer matches gold, else 0.0
223
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
224
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
225
-
226
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
227
- """
228
  import json
229
-
230
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
231
  question = (os.environ.get("QUESTION") or "").strip()
232
  candidate = sys.stdin.read().strip()
233
-
234
  if not candidate:
235
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
236
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
237
  return 0
238
-
239
  at, rt = _tols()
240
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
241
- n_calls = _tool_calls()
242
- eff = _tool_efficiency(n_calls)
243
- print(json.dumps({
244
- "correctness": float(result.reward),
245
- "submission": 1.0,
246
- "tool_efficiency": eff,
247
- }))
248
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
249
- f"correctness={result.reward} method={result.method} "
250
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
251
  return 0
252
 
253
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
 
 
 
 
 
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0015_050_15050710_qa_1/tests/grader.py CHANGED
@@ -1,42 +1,34 @@
1
- """Deterministic short-answer grader — NO LLM judge.
2
 
3
- Tiers (cheapest -> most expensive), all offline/deterministic:
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
- 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
- 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify)
7
-
8
- CLI form (used by tests/test.sh):
9
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
10
- -> reads predicted answer from stdin
11
- -> writes a single float ('1.0' or '0.0') to stdout
12
  """
13
-
14
  from __future__ import annotations
15
-
16
- import os
17
- import re
18
- import sys
19
  from dataclasses import dataclass
20
 
21
-
22
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
23
 
24
 
25
-
26
  @dataclass
27
  class GradeResult:
28
  reward: float
29
- method: str # "exact" | "numeric" | "llm" | "miss"
30
 
31
 
32
  def _normalize(s: str) -> str:
33
  return re.sub(r"\s+", " ", (s or "").strip().lower())
34
 
35
 
36
- def _to_float(s: str) -> float | None:
37
  if not s:
38
  return None
39
- m = _NUMERIC_RE.search(s.replace(",", ""))
40
  if not m:
41
  return None
42
  try:
@@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None:
45
  return None
46
 
47
 
48
- def _math_verify_match(gold: str, candidate: str) -> bool:
49
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
50
-
51
- Catches equivalences the naive float-parse misses: thousands separators,
52
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
53
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
54
- false positive). No network, no LLM.
55
- """
56
- try:
57
- from math_verify import parse, verify
58
-
59
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
60
- except Exception: # noqa: BLE001
61
- return False
62
 
63
 
64
  def _is_clean_number(s: str) -> bool:
65
- """True iff the whole string IS a single number (allowing a leading/trailing
66
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
67
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
68
- the numeric tier must not fire on it (its `_to_float` would grab the leading
69
- '3' and false-positive-match any answer starting with 3)."""
70
  t = (s or "").strip().strip("%$").strip().replace(",", "")
71
  return bool(_NUMERIC_RE.fullmatch(t))
72
 
73
 
74
- def grade(
75
- gold: str,
76
- candidate: str,
77
- *,
78
- question: str = "",
79
- reward_mode: str = "",
80
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
81
- judge_model: str | None = None, # noqa: ARG001
82
- rel_tol: float = 1e-3,
83
- abs_tol: float = 1e-3,
84
- ) -> GradeResult:
85
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
88
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
89
- """
90
 
 
 
91
  if not gold or candidate is None:
92
  return GradeResult(0.0, "miss")
93
 
94
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
95
  if _normalize(gold) == _normalize(candidate):
96
  return GradeResult(1.0, "exact")
97
 
98
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
99
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
100
- # the leading number; those must go to exact/math_verify, which fail closed).
101
- if reward_mode == "numeric" or _is_clean_number(gold):
102
  g, c = _to_float(gold), _to_float(candidate)
103
  if g is not None and c is not None:
104
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
105
  return GradeResult(1.0, "numeric")
 
 
 
 
106
 
107
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
108
  if _math_verify_match(gold, candidate):
109
  return GradeResult(1.0, "math_verify")
110
 
111
  return GradeResult(0.0, "miss")
112
 
113
 
114
- def _tool_calls() -> int | None:
115
- """Number of agent tool calls this rollout, for the efficiency reward.
116
-
117
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
118
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
119
- (efficiency reward becomes null — the harness didn't report a count).
120
- """
121
  try:
122
  with open("/workdir/.n_tool_calls") as fh:
123
  return int(fh.read().strip())
@@ -132,24 +121,17 @@ def _tool_calls() -> int | None:
132
  return None
133
 
134
 
135
- def _tool_efficiency(n_calls: int | None) -> float | None:
136
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
137
-
138
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
139
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
140
- RL reward combiner decides gating/weights.
141
- """
142
- if n_calls is None:
143
  return None
144
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
145
  if budget <= 0:
146
  return None
147
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
148
 
149
 
150
- def _tols() -> tuple[float, float]:
151
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
152
- def _f(name: str) -> float:
153
  try:
154
  return float(os.environ.get(name, "") or 1e-3)
155
  except ValueError:
@@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]:
158
 
159
 
160
  def main_cli() -> int:
161
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
162
-
163
- Inputs (via env vars set by Harbor's [verifier.env]):
164
- EXPECTED_ANSWER — the gold
165
- QUESTION — the original question
166
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
167
-
168
- Predicted answer is read from stdin.
169
- Single float written to stdout. Exit code is always 0.
170
- """
171
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
172
  question = (os.environ.get("QUESTION") or "").strip()
173
  candidate = sys.stdin.read().strip()
174
  at, rt = _tols()
175
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
176
- print(f"{result.reward:.1f}")
177
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
178
- file=sys.stderr)
179
  return 0
180
 
181
 
182
  def main_json() -> int:
183
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
184
-
185
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
186
- correctness — 1.0 iff graded answer matches gold, else 0.0
187
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
188
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
189
-
190
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
191
- """
192
  import json
193
-
194
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
195
  question = (os.environ.get("QUESTION") or "").strip()
196
  candidate = sys.stdin.read().strip()
197
-
198
  if not candidate:
199
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
200
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
201
  return 0
202
-
203
  at, rt = _tols()
204
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
205
- n_calls = _tool_calls()
206
- eff = _tool_efficiency(n_calls)
207
- print(json.dumps({
208
- "correctness": float(result.reward),
209
- "submission": 1.0,
210
- "tool_efficiency": eff,
211
- }))
212
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
213
- f"correctness={result.reward} method={result.method} "
214
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
215
  return 0
216
 
217
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
17
 
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0018_456_18456045_qa_5/tests/grader.py CHANGED
@@ -1,78 +1,34 @@
1
- """Shared three-tier grader.
2
 
3
- Used by both runtimes:
4
- * `env/server.py` — inline inside the `final_answer` ORS @tool method
5
- * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py
6
- and invoked with `python3 /tests/grader.py < /workdir/answer.txt`
7
-
8
- Tiers (cheapest → most expensive):
9
  1. Exact (case-insensitive, whitespace-collapsed)
10
- 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3)
11
- 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt)
12
- — only invoked if OPENAI_API_KEY is set
13
-
14
- CLI form (used by tests/test.sh):
15
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
16
- → reads predicted answer from stdin
17
- → writes a single float ('1.0' or '0.0') to stdout
18
- → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt
19
  """
20
-
21
  from __future__ import annotations
22
-
23
- import os
24
- import re
25
- import sys
26
  from dataclasses import dataclass
27
 
28
-
29
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
30
 
31
- # Locked in PLAN.md §"Locked decisions" — adapted from
32
- # https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py
33
- JUDGE_PROMPT = """You are grading short answers from a data-science agent.
34
- Decide whether the predicted answer is semantically equivalent to the gold answer.
35
-
36
- Rules:
37
- - Case, punctuation, whitespace, articles ("the"), and trailing units don't matter.
38
- - For numbers: predicted must match to the last significant figure of the gold
39
- (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT).
40
- - Extra surrounding prose is fine if the gold value is clearly stated
41
- (gold "5", predicted "There are 5 distinct categories" -> CORRECT).
42
- - Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT).
43
- - Parenthetical annotations in the gold are equivalence hints, not required
44
- (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT;
45
- gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT).
46
- - Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X%
47
- is CORRECT as long as the core numeric value matches
48
- (gold "21.334% in 2014", predicted "21.334" -> CORRECT;
49
- gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch).
50
- - Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one
51
- thing (e.g. "which model?"), predicting either listed value is CORRECT.
52
- - If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED.
53
- - If it commits to a different value -> INCORRECT.
54
-
55
- Question: {question}
56
- Gold answer: {gold}
57
- Predicted answer: {pred}
58
-
59
- Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED)."""
60
-
61
 
62
  @dataclass
63
  class GradeResult:
64
  reward: float
65
- method: str # "exact" | "numeric" | "llm" | "miss"
66
 
67
 
68
  def _normalize(s: str) -> str:
69
  return re.sub(r"\s+", " ", (s or "").strip().lower())
70
 
71
 
72
- def _to_float(s: str) -> float | None:
73
  if not s:
74
  return None
75
- m = _NUMERIC_RE.search(s.replace(",", ""))
76
  if not m:
77
  return None
78
  try:
@@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None:
81
  return None
82
 
83
 
84
- def _math_verify_match(gold: str, candidate: str) -> bool:
85
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
86
-
87
- Catches equivalences the naive float-parse misses: thousands separators,
88
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
89
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
90
- false positive). No network, no LLM.
91
- """
92
- try:
93
- from math_verify import parse, verify
94
-
95
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
96
- except Exception: # noqa: BLE001
97
- return False
98
 
99
 
100
  def _is_clean_number(s: str) -> bool:
101
- """True iff the whole string IS a single number (allowing a leading/trailing
102
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
103
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
104
- the numeric tier must not fire on it (its `_to_float` would grab the leading
105
- '3' and false-positive-match any answer starting with 3)."""
106
  t = (s or "").strip().strip("%$").strip().replace(",", "")
107
  return bool(_NUMERIC_RE.fullmatch(t))
108
 
109
 
110
- def grade(
111
- gold: str,
112
- candidate: str,
113
- *,
114
- question: str = "",
115
- reward_mode: str = "",
116
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
117
- judge_model: str | None = None, # noqa: ARG001
118
- rel_tol: float = 1e-3,
119
- abs_tol: float = 1e-3,
120
- ) -> GradeResult:
121
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
124
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
125
- """
126
 
 
 
127
  if not gold or candidate is None:
128
  return GradeResult(0.0, "miss")
129
 
130
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
131
  if _normalize(gold) == _normalize(candidate):
132
  return GradeResult(1.0, "exact")
133
 
134
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
135
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
136
- # the leading number; those must go to exact/math_verify, which fail closed).
137
- if reward_mode == "numeric" or _is_clean_number(gold):
138
  g, c = _to_float(gold), _to_float(candidate)
139
  if g is not None and c is not None:
140
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
141
  return GradeResult(1.0, "numeric")
 
 
 
 
142
 
143
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
144
  if _math_verify_match(gold, candidate):
145
  return GradeResult(1.0, "math_verify")
146
 
147
  return GradeResult(0.0, "miss")
148
 
149
 
150
- def _tool_calls() -> int | None:
151
- """Number of agent tool calls this rollout, for the efficiency reward.
152
-
153
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
154
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
155
- (efficiency reward becomes null — the harness didn't report a count).
156
- """
157
  try:
158
  with open("/workdir/.n_tool_calls") as fh:
159
  return int(fh.read().strip())
@@ -168,24 +121,17 @@ def _tool_calls() -> int | None:
168
  return None
169
 
170
 
171
- def _tool_efficiency(n_calls: int | None) -> float | None:
172
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
173
-
174
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
175
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
176
- RL reward combiner decides gating/weights.
177
- """
178
- if n_calls is None:
179
  return None
180
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
181
  if budget <= 0:
182
  return None
183
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
184
 
185
 
186
- def _tols() -> tuple[float, float]:
187
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
188
- def _f(name: str) -> float:
189
  try:
190
  return float(os.environ.get(name, "") or 1e-3)
191
  except ValueError:
@@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]:
194
 
195
 
196
  def main_cli() -> int:
197
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
198
-
199
- Inputs (via env vars set by Harbor's [verifier.env]):
200
- EXPECTED_ANSWER — the gold
201
- QUESTION — the original question
202
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
203
-
204
- Predicted answer is read from stdin.
205
- Single float written to stdout. Exit code is always 0.
206
- """
207
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
208
  question = (os.environ.get("QUESTION") or "").strip()
209
  candidate = sys.stdin.read().strip()
210
  at, rt = _tols()
211
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
212
- print(f"{result.reward:.1f}")
213
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
214
- file=sys.stderr)
215
  return 0
216
 
217
 
218
  def main_json() -> int:
219
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
220
-
221
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
222
- correctness — 1.0 iff graded answer matches gold, else 0.0
223
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
224
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
225
-
226
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
227
- """
228
  import json
229
-
230
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
231
  question = (os.environ.get("QUESTION") or "").strip()
232
  candidate = sys.stdin.read().strip()
233
-
234
  if not candidate:
235
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
236
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
237
  return 0
238
-
239
  at, rt = _tols()
240
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
241
- n_calls = _tool_calls()
242
- eff = _tool_efficiency(n_calls)
243
- print(json.dumps({
244
- "correctness": float(result.reward),
245
- "submission": 1.0,
246
- "tool_efficiency": eff,
247
- }))
248
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
249
- f"correctness={result.reward} method={result.method} "
250
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
251
  return 0
252
 
253
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
 
 
 
 
 
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0018_493_18493579_qa_1/tests/grader.py CHANGED
@@ -1,42 +1,34 @@
1
- """Deterministic short-answer grader — NO LLM judge.
2
 
3
- Tiers (cheapest -> most expensive), all offline/deterministic:
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
- 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
- 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify)
7
-
8
- CLI form (used by tests/test.sh):
9
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
10
- -> reads predicted answer from stdin
11
- -> writes a single float ('1.0' or '0.0') to stdout
12
  """
13
-
14
  from __future__ import annotations
15
-
16
- import os
17
- import re
18
- import sys
19
  from dataclasses import dataclass
20
 
21
-
22
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
23
 
24
 
25
-
26
  @dataclass
27
  class GradeResult:
28
  reward: float
29
- method: str # "exact" | "numeric" | "llm" | "miss"
30
 
31
 
32
  def _normalize(s: str) -> str:
33
  return re.sub(r"\s+", " ", (s or "").strip().lower())
34
 
35
 
36
- def _to_float(s: str) -> float | None:
37
  if not s:
38
  return None
39
- m = _NUMERIC_RE.search(s.replace(",", ""))
40
  if not m:
41
  return None
42
  try:
@@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None:
45
  return None
46
 
47
 
48
- def _math_verify_match(gold: str, candidate: str) -> bool:
49
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
50
-
51
- Catches equivalences the naive float-parse misses: thousands separators,
52
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
53
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
54
- false positive). No network, no LLM.
55
- """
56
- try:
57
- from math_verify import parse, verify
58
-
59
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
60
- except Exception: # noqa: BLE001
61
- return False
62
 
63
 
64
  def _is_clean_number(s: str) -> bool:
65
- """True iff the whole string IS a single number (allowing a leading/trailing
66
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
67
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
68
- the numeric tier must not fire on it (its `_to_float` would grab the leading
69
- '3' and false-positive-match any answer starting with 3)."""
70
  t = (s or "").strip().strip("%$").strip().replace(",", "")
71
  return bool(_NUMERIC_RE.fullmatch(t))
72
 
73
 
74
- def grade(
75
- gold: str,
76
- candidate: str,
77
- *,
78
- question: str = "",
79
- reward_mode: str = "",
80
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
81
- judge_model: str | None = None, # noqa: ARG001
82
- rel_tol: float = 1e-3,
83
- abs_tol: float = 1e-3,
84
- ) -> GradeResult:
85
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
88
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
89
- """
90
 
 
 
91
  if not gold or candidate is None:
92
  return GradeResult(0.0, "miss")
93
 
94
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
95
  if _normalize(gold) == _normalize(candidate):
96
  return GradeResult(1.0, "exact")
97
 
98
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
99
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
100
- # the leading number; those must go to exact/math_verify, which fail closed).
101
- if reward_mode == "numeric" or _is_clean_number(gold):
102
  g, c = _to_float(gold), _to_float(candidate)
103
  if g is not None and c is not None:
104
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
105
  return GradeResult(1.0, "numeric")
 
 
 
 
106
 
107
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
108
  if _math_verify_match(gold, candidate):
109
  return GradeResult(1.0, "math_verify")
110
 
111
  return GradeResult(0.0, "miss")
112
 
113
 
114
- def _tool_calls() -> int | None:
115
- """Number of agent tool calls this rollout, for the efficiency reward.
116
-
117
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
118
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
119
- (efficiency reward becomes null — the harness didn't report a count).
120
- """
121
  try:
122
  with open("/workdir/.n_tool_calls") as fh:
123
  return int(fh.read().strip())
@@ -132,24 +121,17 @@ def _tool_calls() -> int | None:
132
  return None
133
 
134
 
135
- def _tool_efficiency(n_calls: int | None) -> float | None:
136
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
137
-
138
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
139
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
140
- RL reward combiner decides gating/weights.
141
- """
142
- if n_calls is None:
143
  return None
144
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
145
  if budget <= 0:
146
  return None
147
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
148
 
149
 
150
- def _tols() -> tuple[float, float]:
151
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
152
- def _f(name: str) -> float:
153
  try:
154
  return float(os.environ.get(name, "") or 1e-3)
155
  except ValueError:
@@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]:
158
 
159
 
160
  def main_cli() -> int:
161
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
162
-
163
- Inputs (via env vars set by Harbor's [verifier.env]):
164
- EXPECTED_ANSWER — the gold
165
- QUESTION — the original question
166
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
167
-
168
- Predicted answer is read from stdin.
169
- Single float written to stdout. Exit code is always 0.
170
- """
171
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
172
  question = (os.environ.get("QUESTION") or "").strip()
173
  candidate = sys.stdin.read().strip()
174
  at, rt = _tols()
175
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
176
- print(f"{result.reward:.1f}")
177
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
178
- file=sys.stderr)
179
  return 0
180
 
181
 
182
  def main_json() -> int:
183
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
184
-
185
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
186
- correctness — 1.0 iff graded answer matches gold, else 0.0
187
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
188
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
189
-
190
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
191
- """
192
  import json
193
-
194
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
195
  question = (os.environ.get("QUESTION") or "").strip()
196
  candidate = sys.stdin.read().strip()
197
-
198
  if not candidate:
199
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
200
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
201
  return 0
202
-
203
  at, rt = _tols()
204
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
205
- n_calls = _tool_calls()
206
- eff = _tool_efficiency(n_calls)
207
- print(json.dumps({
208
- "correctness": float(result.reward),
209
- "submission": 1.0,
210
- "tool_efficiency": eff,
211
- }))
212
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
213
- f"correctness={result.reward} method={result.method} "
214
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
215
  return 0
216
 
217
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
17
 
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0020_216_20216126_qa_2/tests/grader.py CHANGED
@@ -1,42 +1,34 @@
1
- """Deterministic short-answer grader — NO LLM judge.
2
 
3
- Tiers (cheapest -> most expensive), all offline/deterministic:
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
- 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
- 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify)
7
-
8
- CLI form (used by tests/test.sh):
9
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
10
- -> reads predicted answer from stdin
11
- -> writes a single float ('1.0' or '0.0') to stdout
12
  """
13
-
14
  from __future__ import annotations
15
-
16
- import os
17
- import re
18
- import sys
19
  from dataclasses import dataclass
20
 
21
-
22
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
23
 
24
 
25
-
26
  @dataclass
27
  class GradeResult:
28
  reward: float
29
- method: str # "exact" | "numeric" | "llm" | "miss"
30
 
31
 
32
  def _normalize(s: str) -> str:
33
  return re.sub(r"\s+", " ", (s or "").strip().lower())
34
 
35
 
36
- def _to_float(s: str) -> float | None:
37
  if not s:
38
  return None
39
- m = _NUMERIC_RE.search(s.replace(",", ""))
40
  if not m:
41
  return None
42
  try:
@@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None:
45
  return None
46
 
47
 
48
- def _math_verify_match(gold: str, candidate: str) -> bool:
49
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
50
-
51
- Catches equivalences the naive float-parse misses: thousands separators,
52
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
53
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
54
- false positive). No network, no LLM.
55
- """
56
- try:
57
- from math_verify import parse, verify
58
-
59
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
60
- except Exception: # noqa: BLE001
61
- return False
62
 
63
 
64
  def _is_clean_number(s: str) -> bool:
65
- """True iff the whole string IS a single number (allowing a leading/trailing
66
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
67
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
68
- the numeric tier must not fire on it (its `_to_float` would grab the leading
69
- '3' and false-positive-match any answer starting with 3)."""
70
  t = (s or "").strip().strip("%$").strip().replace(",", "")
71
  return bool(_NUMERIC_RE.fullmatch(t))
72
 
73
 
74
- def grade(
75
- gold: str,
76
- candidate: str,
77
- *,
78
- question: str = "",
79
- reward_mode: str = "",
80
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
81
- judge_model: str | None = None, # noqa: ARG001
82
- rel_tol: float = 1e-3,
83
- abs_tol: float = 1e-3,
84
- ) -> GradeResult:
85
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
88
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
89
- """
90
 
 
 
91
  if not gold or candidate is None:
92
  return GradeResult(0.0, "miss")
93
 
94
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
95
  if _normalize(gold) == _normalize(candidate):
96
  return GradeResult(1.0, "exact")
97
 
98
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
99
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
100
- # the leading number; those must go to exact/math_verify, which fail closed).
101
- if reward_mode == "numeric" or _is_clean_number(gold):
102
  g, c = _to_float(gold), _to_float(candidate)
103
  if g is not None and c is not None:
104
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
105
  return GradeResult(1.0, "numeric")
 
 
 
 
106
 
107
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
108
  if _math_verify_match(gold, candidate):
109
  return GradeResult(1.0, "math_verify")
110
 
111
  return GradeResult(0.0, "miss")
112
 
113
 
114
- def _tool_calls() -> int | None:
115
- """Number of agent tool calls this rollout, for the efficiency reward.
116
-
117
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
118
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
119
- (efficiency reward becomes null — the harness didn't report a count).
120
- """
121
  try:
122
  with open("/workdir/.n_tool_calls") as fh:
123
  return int(fh.read().strip())
@@ -132,24 +121,17 @@ def _tool_calls() -> int | None:
132
  return None
133
 
134
 
135
- def _tool_efficiency(n_calls: int | None) -> float | None:
136
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
137
-
138
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
139
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
140
- RL reward combiner decides gating/weights.
141
- """
142
- if n_calls is None:
143
  return None
144
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
145
  if budget <= 0:
146
  return None
147
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
148
 
149
 
150
- def _tols() -> tuple[float, float]:
151
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
152
- def _f(name: str) -> float:
153
  try:
154
  return float(os.environ.get(name, "") or 1e-3)
155
  except ValueError:
@@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]:
158
 
159
 
160
  def main_cli() -> int:
161
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
162
-
163
- Inputs (via env vars set by Harbor's [verifier.env]):
164
- EXPECTED_ANSWER — the gold
165
- QUESTION — the original question
166
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
167
-
168
- Predicted answer is read from stdin.
169
- Single float written to stdout. Exit code is always 0.
170
- """
171
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
172
  question = (os.environ.get("QUESTION") or "").strip()
173
  candidate = sys.stdin.read().strip()
174
  at, rt = _tols()
175
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
176
- print(f"{result.reward:.1f}")
177
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
178
- file=sys.stderr)
179
  return 0
180
 
181
 
182
  def main_json() -> int:
183
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
184
-
185
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
186
- correctness — 1.0 iff graded answer matches gold, else 0.0
187
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
188
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
189
-
190
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
191
- """
192
  import json
193
-
194
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
195
  question = (os.environ.get("QUESTION") or "").strip()
196
  candidate = sys.stdin.read().strip()
197
-
198
  if not candidate:
199
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
200
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
201
  return 0
202
-
203
  at, rt = _tols()
204
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
205
- n_calls = _tool_calls()
206
- eff = _tool_efficiency(n_calls)
207
- print(json.dumps({
208
- "correctness": float(result.reward),
209
- "submission": 1.0,
210
- "tool_efficiency": eff,
211
- }))
212
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
213
- f"correctness={result.reward} method={result.method} "
214
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
215
  return 0
216
 
217
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
17
 
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0020_613_20613845_qa_4/tests/grader.py CHANGED
@@ -1,42 +1,34 @@
1
- """Deterministic short-answer grader — NO LLM judge.
2
 
3
- Tiers (cheapest -> most expensive), all offline/deterministic:
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
- 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
- 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify)
7
-
8
- CLI form (used by tests/test.sh):
9
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
10
- -> reads predicted answer from stdin
11
- -> writes a single float ('1.0' or '0.0') to stdout
12
  """
13
-
14
  from __future__ import annotations
15
-
16
- import os
17
- import re
18
- import sys
19
  from dataclasses import dataclass
20
 
21
-
22
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
23
 
24
 
25
-
26
  @dataclass
27
  class GradeResult:
28
  reward: float
29
- method: str # "exact" | "numeric" | "llm" | "miss"
30
 
31
 
32
  def _normalize(s: str) -> str:
33
  return re.sub(r"\s+", " ", (s or "").strip().lower())
34
 
35
 
36
- def _to_float(s: str) -> float | None:
37
  if not s:
38
  return None
39
- m = _NUMERIC_RE.search(s.replace(",", ""))
40
  if not m:
41
  return None
42
  try:
@@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None:
45
  return None
46
 
47
 
48
- def _math_verify_match(gold: str, candidate: str) -> bool:
49
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
50
-
51
- Catches equivalences the naive float-parse misses: thousands separators,
52
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
53
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
54
- false positive). No network, no LLM.
55
- """
56
- try:
57
- from math_verify import parse, verify
58
-
59
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
60
- except Exception: # noqa: BLE001
61
- return False
62
 
63
 
64
  def _is_clean_number(s: str) -> bool:
65
- """True iff the whole string IS a single number (allowing a leading/trailing
66
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
67
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
68
- the numeric tier must not fire on it (its `_to_float` would grab the leading
69
- '3' and false-positive-match any answer starting with 3)."""
70
  t = (s or "").strip().strip("%$").strip().replace(",", "")
71
  return bool(_NUMERIC_RE.fullmatch(t))
72
 
73
 
74
- def grade(
75
- gold: str,
76
- candidate: str,
77
- *,
78
- question: str = "",
79
- reward_mode: str = "",
80
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
81
- judge_model: str | None = None, # noqa: ARG001
82
- rel_tol: float = 1e-3,
83
- abs_tol: float = 1e-3,
84
- ) -> GradeResult:
85
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
88
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
89
- """
90
 
 
 
91
  if not gold or candidate is None:
92
  return GradeResult(0.0, "miss")
93
 
94
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
95
  if _normalize(gold) == _normalize(candidate):
96
  return GradeResult(1.0, "exact")
97
 
98
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
99
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
100
- # the leading number; those must go to exact/math_verify, which fail closed).
101
- if reward_mode == "numeric" or _is_clean_number(gold):
102
  g, c = _to_float(gold), _to_float(candidate)
103
  if g is not None and c is not None:
104
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
105
  return GradeResult(1.0, "numeric")
 
 
 
 
106
 
107
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
108
  if _math_verify_match(gold, candidate):
109
  return GradeResult(1.0, "math_verify")
110
 
111
  return GradeResult(0.0, "miss")
112
 
113
 
114
- def _tool_calls() -> int | None:
115
- """Number of agent tool calls this rollout, for the efficiency reward.
116
-
117
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
118
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
119
- (efficiency reward becomes null — the harness didn't report a count).
120
- """
121
  try:
122
  with open("/workdir/.n_tool_calls") as fh:
123
  return int(fh.read().strip())
@@ -132,24 +121,17 @@ def _tool_calls() -> int | None:
132
  return None
133
 
134
 
135
- def _tool_efficiency(n_calls: int | None) -> float | None:
136
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
137
-
138
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
139
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
140
- RL reward combiner decides gating/weights.
141
- """
142
- if n_calls is None:
143
  return None
144
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
145
  if budget <= 0:
146
  return None
147
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
148
 
149
 
150
- def _tols() -> tuple[float, float]:
151
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
152
- def _f(name: str) -> float:
153
  try:
154
  return float(os.environ.get(name, "") or 1e-3)
155
  except ValueError:
@@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]:
158
 
159
 
160
  def main_cli() -> int:
161
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
162
-
163
- Inputs (via env vars set by Harbor's [verifier.env]):
164
- EXPECTED_ANSWER — the gold
165
- QUESTION — the original question
166
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
167
-
168
- Predicted answer is read from stdin.
169
- Single float written to stdout. Exit code is always 0.
170
- """
171
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
172
  question = (os.environ.get("QUESTION") or "").strip()
173
  candidate = sys.stdin.read().strip()
174
  at, rt = _tols()
175
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
176
- print(f"{result.reward:.1f}")
177
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
178
- file=sys.stderr)
179
  return 0
180
 
181
 
182
  def main_json() -> int:
183
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
184
-
185
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
186
- correctness — 1.0 iff graded answer matches gold, else 0.0
187
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
188
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
189
-
190
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
191
- """
192
  import json
193
-
194
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
195
  question = (os.environ.get("QUESTION") or "").strip()
196
  candidate = sys.stdin.read().strip()
197
-
198
  if not candidate:
199
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
200
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
201
  return 0
202
-
203
  at, rt = _tols()
204
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
205
- n_calls = _tool_calls()
206
- eff = _tool_efficiency(n_calls)
207
- print(json.dumps({
208
- "correctness": float(result.reward),
209
- "submission": 1.0,
210
- "tool_efficiency": eff,
211
- }))
212
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
213
- f"correctness={result.reward} method={result.method} "
214
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
215
  return 0
216
 
217
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
17
 
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0020_756_20756026_qa_2/tests/grader.py CHANGED
@@ -1,42 +1,34 @@
1
- """Deterministic short-answer grader — NO LLM judge.
2
 
3
- Tiers (cheapest -> most expensive), all offline/deterministic:
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
- 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
- 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify)
7
-
8
- CLI form (used by tests/test.sh):
9
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
10
- -> reads predicted answer from stdin
11
- -> writes a single float ('1.0' or '0.0') to stdout
12
  """
13
-
14
  from __future__ import annotations
15
-
16
- import os
17
- import re
18
- import sys
19
  from dataclasses import dataclass
20
 
21
-
22
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
23
 
24
 
25
-
26
  @dataclass
27
  class GradeResult:
28
  reward: float
29
- method: str # "exact" | "numeric" | "llm" | "miss"
30
 
31
 
32
  def _normalize(s: str) -> str:
33
  return re.sub(r"\s+", " ", (s or "").strip().lower())
34
 
35
 
36
- def _to_float(s: str) -> float | None:
37
  if not s:
38
  return None
39
- m = _NUMERIC_RE.search(s.replace(",", ""))
40
  if not m:
41
  return None
42
  try:
@@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None:
45
  return None
46
 
47
 
48
- def _math_verify_match(gold: str, candidate: str) -> bool:
49
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
50
-
51
- Catches equivalences the naive float-parse misses: thousands separators,
52
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
53
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
54
- false positive). No network, no LLM.
55
- """
56
- try:
57
- from math_verify import parse, verify
58
-
59
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
60
- except Exception: # noqa: BLE001
61
- return False
62
 
63
 
64
  def _is_clean_number(s: str) -> bool:
65
- """True iff the whole string IS a single number (allowing a leading/trailing
66
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
67
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
68
- the numeric tier must not fire on it (its `_to_float` would grab the leading
69
- '3' and false-positive-match any answer starting with 3)."""
70
  t = (s or "").strip().strip("%$").strip().replace(",", "")
71
  return bool(_NUMERIC_RE.fullmatch(t))
72
 
73
 
74
- def grade(
75
- gold: str,
76
- candidate: str,
77
- *,
78
- question: str = "",
79
- reward_mode: str = "",
80
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
81
- judge_model: str | None = None, # noqa: ARG001
82
- rel_tol: float = 1e-3,
83
- abs_tol: float = 1e-3,
84
- ) -> GradeResult:
85
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
88
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
89
- """
90
 
 
 
91
  if not gold or candidate is None:
92
  return GradeResult(0.0, "miss")
93
 
94
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
95
  if _normalize(gold) == _normalize(candidate):
96
  return GradeResult(1.0, "exact")
97
 
98
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
99
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
100
- # the leading number; those must go to exact/math_verify, which fail closed).
101
- if reward_mode == "numeric" or _is_clean_number(gold):
102
  g, c = _to_float(gold), _to_float(candidate)
103
  if g is not None and c is not None:
104
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
105
  return GradeResult(1.0, "numeric")
 
 
 
 
106
 
107
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
108
  if _math_verify_match(gold, candidate):
109
  return GradeResult(1.0, "math_verify")
110
 
111
  return GradeResult(0.0, "miss")
112
 
113
 
114
- def _tool_calls() -> int | None:
115
- """Number of agent tool calls this rollout, for the efficiency reward.
116
-
117
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
118
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
119
- (efficiency reward becomes null — the harness didn't report a count).
120
- """
121
  try:
122
  with open("/workdir/.n_tool_calls") as fh:
123
  return int(fh.read().strip())
@@ -132,24 +121,17 @@ def _tool_calls() -> int | None:
132
  return None
133
 
134
 
135
- def _tool_efficiency(n_calls: int | None) -> float | None:
136
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
137
-
138
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
139
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
140
- RL reward combiner decides gating/weights.
141
- """
142
- if n_calls is None:
143
  return None
144
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
145
  if budget <= 0:
146
  return None
147
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
148
 
149
 
150
- def _tols() -> tuple[float, float]:
151
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
152
- def _f(name: str) -> float:
153
  try:
154
  return float(os.environ.get(name, "") or 1e-3)
155
  except ValueError:
@@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]:
158
 
159
 
160
  def main_cli() -> int:
161
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
162
-
163
- Inputs (via env vars set by Harbor's [verifier.env]):
164
- EXPECTED_ANSWER — the gold
165
- QUESTION — the original question
166
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
167
-
168
- Predicted answer is read from stdin.
169
- Single float written to stdout. Exit code is always 0.
170
- """
171
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
172
  question = (os.environ.get("QUESTION") or "").strip()
173
  candidate = sys.stdin.read().strip()
174
  at, rt = _tols()
175
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
176
- print(f"{result.reward:.1f}")
177
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
178
- file=sys.stderr)
179
  return 0
180
 
181
 
182
  def main_json() -> int:
183
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
184
-
185
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
186
- correctness — 1.0 iff graded answer matches gold, else 0.0
187
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
188
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
189
-
190
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
191
- """
192
  import json
193
-
194
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
195
  question = (os.environ.get("QUESTION") or "").strip()
196
  candidate = sys.stdin.read().strip()
197
-
198
  if not candidate:
199
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
200
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
201
  return 0
202
-
203
  at, rt = _tols()
204
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
205
- n_calls = _tool_calls()
206
- eff = _tool_efficiency(n_calls)
207
- print(json.dumps({
208
- "correctness": float(result.reward),
209
- "submission": 1.0,
210
- "tool_efficiency": eff,
211
- }))
212
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
213
- f"correctness={result.reward} method={result.method} "
214
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
215
  return 0
216
 
217
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
17
 
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0021_299_21299002_qa_3/tests/grader.py CHANGED
@@ -1,78 +1,34 @@
1
- """Shared three-tier grader.
2
 
3
- Used by both runtimes:
4
- * `env/server.py` — inline inside the `final_answer` ORS @tool method
5
- * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py
6
- and invoked with `python3 /tests/grader.py < /workdir/answer.txt`
7
-
8
- Tiers (cheapest → most expensive):
9
  1. Exact (case-insensitive, whitespace-collapsed)
10
- 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3)
11
- 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt)
12
- — only invoked if OPENAI_API_KEY is set
13
-
14
- CLI form (used by tests/test.sh):
15
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
16
- → reads predicted answer from stdin
17
- → writes a single float ('1.0' or '0.0') to stdout
18
- → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt
19
  """
20
-
21
  from __future__ import annotations
22
-
23
- import os
24
- import re
25
- import sys
26
  from dataclasses import dataclass
27
 
28
-
29
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
30
 
31
- # Locked in PLAN.md §"Locked decisions" — adapted from
32
- # https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py
33
- JUDGE_PROMPT = """You are grading short answers from a data-science agent.
34
- Decide whether the predicted answer is semantically equivalent to the gold answer.
35
-
36
- Rules:
37
- - Case, punctuation, whitespace, articles ("the"), and trailing units don't matter.
38
- - For numbers: predicted must match to the last significant figure of the gold
39
- (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT).
40
- - Extra surrounding prose is fine if the gold value is clearly stated
41
- (gold "5", predicted "There are 5 distinct categories" -> CORRECT).
42
- - Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT).
43
- - Parenthetical annotations in the gold are equivalence hints, not required
44
- (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT;
45
- gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT).
46
- - Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X%
47
- is CORRECT as long as the core numeric value matches
48
- (gold "21.334% in 2014", predicted "21.334" -> CORRECT;
49
- gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch).
50
- - Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one
51
- thing (e.g. "which model?"), predicting either listed value is CORRECT.
52
- - If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED.
53
- - If it commits to a different value -> INCORRECT.
54
-
55
- Question: {question}
56
- Gold answer: {gold}
57
- Predicted answer: {pred}
58
-
59
- Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED)."""
60
-
61
 
62
  @dataclass
63
  class GradeResult:
64
  reward: float
65
- method: str # "exact" | "numeric" | "llm" | "miss"
66
 
67
 
68
  def _normalize(s: str) -> str:
69
  return re.sub(r"\s+", " ", (s or "").strip().lower())
70
 
71
 
72
- def _to_float(s: str) -> float | None:
73
  if not s:
74
  return None
75
- m = _NUMERIC_RE.search(s.replace(",", ""))
76
  if not m:
77
  return None
78
  try:
@@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None:
81
  return None
82
 
83
 
84
- def _math_verify_match(gold: str, candidate: str) -> bool:
85
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
86
-
87
- Catches equivalences the naive float-parse misses: thousands separators,
88
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
89
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
90
- false positive). No network, no LLM.
91
- """
92
- try:
93
- from math_verify import parse, verify
94
-
95
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
96
- except Exception: # noqa: BLE001
97
- return False
98
 
99
 
100
  def _is_clean_number(s: str) -> bool:
101
- """True iff the whole string IS a single number (allowing a leading/trailing
102
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
103
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
104
- the numeric tier must not fire on it (its `_to_float` would grab the leading
105
- '3' and false-positive-match any answer starting with 3)."""
106
  t = (s or "").strip().strip("%$").strip().replace(",", "")
107
  return bool(_NUMERIC_RE.fullmatch(t))
108
 
109
 
110
- def grade(
111
- gold: str,
112
- candidate: str,
113
- *,
114
- question: str = "",
115
- reward_mode: str = "",
116
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
117
- judge_model: str | None = None, # noqa: ARG001
118
- rel_tol: float = 1e-3,
119
- abs_tol: float = 1e-3,
120
- ) -> GradeResult:
121
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
124
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
125
- """
126
 
 
 
127
  if not gold or candidate is None:
128
  return GradeResult(0.0, "miss")
129
 
130
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
131
  if _normalize(gold) == _normalize(candidate):
132
  return GradeResult(1.0, "exact")
133
 
134
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
135
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
136
- # the leading number; those must go to exact/math_verify, which fail closed).
137
- if reward_mode == "numeric" or _is_clean_number(gold):
138
  g, c = _to_float(gold), _to_float(candidate)
139
  if g is not None and c is not None:
140
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
141
  return GradeResult(1.0, "numeric")
 
 
 
 
142
 
143
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
144
  if _math_verify_match(gold, candidate):
145
  return GradeResult(1.0, "math_verify")
146
 
147
  return GradeResult(0.0, "miss")
148
 
149
 
150
- def _tool_calls() -> int | None:
151
- """Number of agent tool calls this rollout, for the efficiency reward.
152
-
153
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
154
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
155
- (efficiency reward becomes null — the harness didn't report a count).
156
- """
157
  try:
158
  with open("/workdir/.n_tool_calls") as fh:
159
  return int(fh.read().strip())
@@ -168,24 +121,17 @@ def _tool_calls() -> int | None:
168
  return None
169
 
170
 
171
- def _tool_efficiency(n_calls: int | None) -> float | None:
172
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
173
-
174
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
175
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
176
- RL reward combiner decides gating/weights.
177
- """
178
- if n_calls is None:
179
  return None
180
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
181
  if budget <= 0:
182
  return None
183
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
184
 
185
 
186
- def _tols() -> tuple[float, float]:
187
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
188
- def _f(name: str) -> float:
189
  try:
190
  return float(os.environ.get(name, "") or 1e-3)
191
  except ValueError:
@@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]:
194
 
195
 
196
  def main_cli() -> int:
197
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
198
-
199
- Inputs (via env vars set by Harbor's [verifier.env]):
200
- EXPECTED_ANSWER — the gold
201
- QUESTION — the original question
202
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
203
-
204
- Predicted answer is read from stdin.
205
- Single float written to stdout. Exit code is always 0.
206
- """
207
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
208
  question = (os.environ.get("QUESTION") or "").strip()
209
  candidate = sys.stdin.read().strip()
210
  at, rt = _tols()
211
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
212
- print(f"{result.reward:.1f}")
213
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
214
- file=sys.stderr)
215
  return 0
216
 
217
 
218
  def main_json() -> int:
219
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
220
-
221
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
222
- correctness — 1.0 iff graded answer matches gold, else 0.0
223
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
224
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
225
-
226
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
227
- """
228
  import json
229
-
230
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
231
  question = (os.environ.get("QUESTION") or "").strip()
232
  candidate = sys.stdin.read().strip()
233
-
234
  if not candidate:
235
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
236
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
237
  return 0
238
-
239
  at, rt = _tols()
240
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
241
- n_calls = _tool_calls()
242
- eff = _tool_efficiency(n_calls)
243
- print(json.dumps({
244
- "correctness": float(result.reward),
245
- "submission": 1.0,
246
- "tool_efficiency": eff,
247
- }))
248
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
249
- f"correctness={result.reward} method={result.method} "
250
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
251
  return 0
252
 
253
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
 
 
 
 
 
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0022_193_22193578_qa_5/environment/Dockerfile ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ FROM docker.io/savatar101/env-data-agent-train:base
2
+ WORKDIR /workdir
tasks/0022_193_22193578_qa_5/environment/pull_bucket.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pull this task's bucket prefix into /home/user/input/.
2
+
3
+ Invoked by Harbor's [environment.healthcheck] command (declared in task.toml)
4
+ — runs after container start, before the agent. Idempotent: skips work if
5
+ files are already present from a prior pull.
6
+ """
7
+
8
+ import os
9
+ import sys
10
+ from pathlib import Path
11
+
12
+ from huggingface_hub import download_bucket_files, list_bucket_tree
13
+
14
+
15
+ def main() -> int:
16
+ bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all"
17
+ prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/"
18
+ dest = Path("/home/user/input")
19
+ dest.mkdir(parents=True, exist_ok=True)
20
+
21
+ existing = [p for p in dest.iterdir() if p.is_file()]
22
+ if existing:
23
+ print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True)
24
+ return 0
25
+
26
+ targets = [
27
+ (it.path, str(dest / Path(it.path).name))
28
+ for it in list_bucket_tree(bucket, prefix=prefix, recursive=True)
29
+ if getattr(it, "type", None) == "file"
30
+ ]
31
+ if not targets:
32
+ print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True)
33
+ return 2
34
+
35
+ download_bucket_files(bucket, files=targets)
36
+ print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True)
37
+ return 0
38
+
39
+
40
+ if __name__ == "__main__":
41
+ sys.exit(main())
tasks/0022_193_22193578_qa_5/tests/grader.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
+
3
+ Tiers (all offline/deterministic):
4
+ 1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
10
+ """
11
+ from __future__ import annotations
12
+ import os, re, sys
13
+ from dataclasses import dataclass
14
+
15
+ _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
+
17
+
18
+ @dataclass
19
+ class GradeResult:
20
+ reward: float
21
+ method: str
22
+
23
+
24
+ def _normalize(s: str) -> str:
25
+ return re.sub(r"\s+", " ", (s or "").strip().lower())
26
+
27
+
28
+ def _to_float(s: str):
29
+ if not s:
30
+ return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
+ if not m:
33
+ return None
34
+ try:
35
+ return float(m.group(0))
36
+ except ValueError:
37
+ return None
38
+
39
+
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
42
+
43
+
44
+ def _is_clean_number(s: str) -> bool:
45
+ t = (s or "").strip().strip("%$").strip().replace(",", "")
46
+ return bool(_NUMERIC_RE.fullmatch(t))
47
+
48
+
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
+
76
+
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
+ if not gold or candidate is None:
80
+ return GradeResult(0.0, "miss")
81
+
82
+ # Tier 1: exact
83
+ if _normalize(gold) == _normalize(candidate):
84
+ return GradeResult(1.0, "exact")
85
+
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
88
+ g, c = _to_float(gold), _to_float(candidate)
89
+ if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
+ return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
+
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
+ if _math_verify_match(gold, candidate):
104
+ return GradeResult(1.0, "math_verify")
105
+
106
+ return GradeResult(0.0, "miss")
107
+
108
+
109
+ def _tool_calls():
110
+ try:
111
+ with open("/workdir/.n_tool_calls") as fh:
112
+ return int(fh.read().strip())
113
+ except (OSError, ValueError):
114
+ pass
115
+ raw = os.environ.get("N_TOOL_CALLS")
116
+ if raw is not None:
117
+ try:
118
+ return int(str(raw).strip())
119
+ except ValueError:
120
+ return None
121
+ return None
122
+
123
+
124
+ def _tool_efficiency(n):
125
+ if n is None:
126
+ return None
127
+ budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
+ if budget <= 0:
129
+ return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
+
132
+
133
+ def _tols():
134
+ def _f(name):
135
+ try:
136
+ return float(os.environ.get(name, "") or 1e-3)
137
+ except ValueError:
138
+ return 1e-3
139
+ return _f("ATOL"), _f("RTOL")
140
+
141
+
142
+ def main_cli() -> int:
143
+ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
+ question = (os.environ.get("QUESTION") or "").strip()
145
+ candidate = sys.stdin.read().strip()
146
+ at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
150
+ return 0
151
+
152
+
153
+ def main_json() -> int:
154
+ import json
155
+ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
+ question = (os.environ.get("QUESTION") or "").strip()
157
+ candidate = sys.stdin.read().strip()
158
+ if not candidate:
159
+ print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
160
+ return 0
161
+ at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
166
+ return 0
167
+
168
+
169
+ if __name__ == "__main__":
170
+ if "--json" in sys.argv[1:]:
171
+ raise SystemExit(main_json())
172
+ raise SystemExit(main_cli())
tasks/0022_193_22193578_qa_5/tests/test.sh ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -u
3
+ mkdir -p /logs/verifier
4
+
5
+ answer_path="/workdir/answer.txt"
6
+ if [ ! -s "$answer_path" ]; then
7
+ echo "0.0" > /logs/verifier/reward.txt
8
+ echo "[grader] no answer at $answer_path" >&2
9
+ exit 0
10
+ fi
11
+
12
+ pip install --quiet math-verify >/dev/null 2>&1 || true
13
+ python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt
tasks/0022_916_22916338_qa_5/tests/grader.py CHANGED
@@ -1,78 +1,34 @@
1
- """Shared three-tier grader.
2
 
3
- Used by both runtimes:
4
- * `env/server.py` — inline inside the `final_answer` ORS @tool method
5
- * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py
6
- and invoked with `python3 /tests/grader.py < /workdir/answer.txt`
7
-
8
- Tiers (cheapest → most expensive):
9
  1. Exact (case-insensitive, whitespace-collapsed)
10
- 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3)
11
- 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt)
12
- — only invoked if OPENAI_API_KEY is set
13
-
14
- CLI form (used by tests/test.sh):
15
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
16
- → reads predicted answer from stdin
17
- → writes a single float ('1.0' or '0.0') to stdout
18
- → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt
19
  """
20
-
21
  from __future__ import annotations
22
-
23
- import os
24
- import re
25
- import sys
26
  from dataclasses import dataclass
27
 
28
-
29
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
30
 
31
- # Locked in PLAN.md §"Locked decisions" — adapted from
32
- # https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py
33
- JUDGE_PROMPT = """You are grading short answers from a data-science agent.
34
- Decide whether the predicted answer is semantically equivalent to the gold answer.
35
-
36
- Rules:
37
- - Case, punctuation, whitespace, articles ("the"), and trailing units don't matter.
38
- - For numbers: predicted must match to the last significant figure of the gold
39
- (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT).
40
- - Extra surrounding prose is fine if the gold value is clearly stated
41
- (gold "5", predicted "There are 5 distinct categories" -> CORRECT).
42
- - Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT).
43
- - Parenthetical annotations in the gold are equivalence hints, not required
44
- (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT;
45
- gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT).
46
- - Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X%
47
- is CORRECT as long as the core numeric value matches
48
- (gold "21.334% in 2014", predicted "21.334" -> CORRECT;
49
- gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch).
50
- - Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one
51
- thing (e.g. "which model?"), predicting either listed value is CORRECT.
52
- - If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED.
53
- - If it commits to a different value -> INCORRECT.
54
-
55
- Question: {question}
56
- Gold answer: {gold}
57
- Predicted answer: {pred}
58
-
59
- Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED)."""
60
-
61
 
62
  @dataclass
63
  class GradeResult:
64
  reward: float
65
- method: str # "exact" | "numeric" | "llm" | "miss"
66
 
67
 
68
  def _normalize(s: str) -> str:
69
  return re.sub(r"\s+", " ", (s or "").strip().lower())
70
 
71
 
72
- def _to_float(s: str) -> float | None:
73
  if not s:
74
  return None
75
- m = _NUMERIC_RE.search(s.replace(",", ""))
76
  if not m:
77
  return None
78
  try:
@@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None:
81
  return None
82
 
83
 
84
- def _math_verify_match(gold: str, candidate: str) -> bool:
85
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
86
-
87
- Catches equivalences the naive float-parse misses: thousands separators,
88
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
89
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
90
- false positive). No network, no LLM.
91
- """
92
- try:
93
- from math_verify import parse, verify
94
-
95
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
96
- except Exception: # noqa: BLE001
97
- return False
98
 
99
 
100
  def _is_clean_number(s: str) -> bool:
101
- """True iff the whole string IS a single number (allowing a leading/trailing
102
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
103
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
104
- the numeric tier must not fire on it (its `_to_float` would grab the leading
105
- '3' and false-positive-match any answer starting with 3)."""
106
  t = (s or "").strip().strip("%$").strip().replace(",", "")
107
  return bool(_NUMERIC_RE.fullmatch(t))
108
 
109
 
110
- def grade(
111
- gold: str,
112
- candidate: str,
113
- *,
114
- question: str = "",
115
- reward_mode: str = "",
116
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
117
- judge_model: str | None = None, # noqa: ARG001
118
- rel_tol: float = 1e-3,
119
- abs_tol: float = 1e-3,
120
- ) -> GradeResult:
121
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
124
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
125
- """
126
 
 
 
127
  if not gold or candidate is None:
128
  return GradeResult(0.0, "miss")
129
 
130
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
131
  if _normalize(gold) == _normalize(candidate):
132
  return GradeResult(1.0, "exact")
133
 
134
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
135
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
136
- # the leading number; those must go to exact/math_verify, which fail closed).
137
- if reward_mode == "numeric" or _is_clean_number(gold):
138
  g, c = _to_float(gold), _to_float(candidate)
139
  if g is not None and c is not None:
140
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
141
  return GradeResult(1.0, "numeric")
 
 
 
 
142
 
143
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
144
  if _math_verify_match(gold, candidate):
145
  return GradeResult(1.0, "math_verify")
146
 
147
  return GradeResult(0.0, "miss")
148
 
149
 
150
- def _tool_calls() -> int | None:
151
- """Number of agent tool calls this rollout, for the efficiency reward.
152
-
153
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
154
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
155
- (efficiency reward becomes null — the harness didn't report a count).
156
- """
157
  try:
158
  with open("/workdir/.n_tool_calls") as fh:
159
  return int(fh.read().strip())
@@ -168,24 +121,17 @@ def _tool_calls() -> int | None:
168
  return None
169
 
170
 
171
- def _tool_efficiency(n_calls: int | None) -> float | None:
172
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
173
-
174
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
175
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
176
- RL reward combiner decides gating/weights.
177
- """
178
- if n_calls is None:
179
  return None
180
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
181
  if budget <= 0:
182
  return None
183
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
184
 
185
 
186
- def _tols() -> tuple[float, float]:
187
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
188
- def _f(name: str) -> float:
189
  try:
190
  return float(os.environ.get(name, "") or 1e-3)
191
  except ValueError:
@@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]:
194
 
195
 
196
  def main_cli() -> int:
197
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
198
-
199
- Inputs (via env vars set by Harbor's [verifier.env]):
200
- EXPECTED_ANSWER — the gold
201
- QUESTION — the original question
202
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
203
-
204
- Predicted answer is read from stdin.
205
- Single float written to stdout. Exit code is always 0.
206
- """
207
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
208
  question = (os.environ.get("QUESTION") or "").strip()
209
  candidate = sys.stdin.read().strip()
210
  at, rt = _tols()
211
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
212
- print(f"{result.reward:.1f}")
213
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
214
- file=sys.stderr)
215
  return 0
216
 
217
 
218
  def main_json() -> int:
219
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
220
-
221
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
222
- correctness — 1.0 iff graded answer matches gold, else 0.0
223
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
224
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
225
-
226
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
227
- """
228
  import json
229
-
230
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
231
  question = (os.environ.get("QUESTION") or "").strip()
232
  candidate = sys.stdin.read().strip()
233
-
234
  if not candidate:
235
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
236
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
237
  return 0
238
-
239
  at, rt = _tols()
240
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
241
- n_calls = _tool_calls()
242
- eff = _tool_efficiency(n_calls)
243
- print(json.dumps({
244
- "correctness": float(result.reward),
245
- "submission": 1.0,
246
- "tool_efficiency": eff,
247
- }))
248
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
249
- f"correctness={result.reward} method={result.method} "
250
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
251
  return 0
252
 
253
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
 
 
 
 
 
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0023_468_23468316_qa_3/tests/grader.py CHANGED
@@ -1,42 +1,34 @@
1
- """Deterministic short-answer grader — NO LLM judge.
2
 
3
- Tiers (cheapest -> most expensive), all offline/deterministic:
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
- 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
- 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify)
7
-
8
- CLI form (used by tests/test.sh):
9
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
10
- -> reads predicted answer from stdin
11
- -> writes a single float ('1.0' or '0.0') to stdout
12
  """
13
-
14
  from __future__ import annotations
15
-
16
- import os
17
- import re
18
- import sys
19
  from dataclasses import dataclass
20
 
21
-
22
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
23
 
24
 
25
-
26
  @dataclass
27
  class GradeResult:
28
  reward: float
29
- method: str # "exact" | "numeric" | "llm" | "miss"
30
 
31
 
32
  def _normalize(s: str) -> str:
33
  return re.sub(r"\s+", " ", (s or "").strip().lower())
34
 
35
 
36
- def _to_float(s: str) -> float | None:
37
  if not s:
38
  return None
39
- m = _NUMERIC_RE.search(s.replace(",", ""))
40
  if not m:
41
  return None
42
  try:
@@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None:
45
  return None
46
 
47
 
48
- def _math_verify_match(gold: str, candidate: str) -> bool:
49
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
50
-
51
- Catches equivalences the naive float-parse misses: thousands separators,
52
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
53
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
54
- false positive). No network, no LLM.
55
- """
56
- try:
57
- from math_verify import parse, verify
58
-
59
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
60
- except Exception: # noqa: BLE001
61
- return False
62
 
63
 
64
  def _is_clean_number(s: str) -> bool:
65
- """True iff the whole string IS a single number (allowing a leading/trailing
66
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
67
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
68
- the numeric tier must not fire on it (its `_to_float` would grab the leading
69
- '3' and false-positive-match any answer starting with 3)."""
70
  t = (s or "").strip().strip("%$").strip().replace(",", "")
71
  return bool(_NUMERIC_RE.fullmatch(t))
72
 
73
 
74
- def grade(
75
- gold: str,
76
- candidate: str,
77
- *,
78
- question: str = "",
79
- reward_mode: str = "",
80
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
81
- judge_model: str | None = None, # noqa: ARG001
82
- rel_tol: float = 1e-3,
83
- abs_tol: float = 1e-3,
84
- ) -> GradeResult:
85
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
88
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
89
- """
90
 
 
 
91
  if not gold or candidate is None:
92
  return GradeResult(0.0, "miss")
93
 
94
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
95
  if _normalize(gold) == _normalize(candidate):
96
  return GradeResult(1.0, "exact")
97
 
98
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
99
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
100
- # the leading number; those must go to exact/math_verify, which fail closed).
101
- if reward_mode == "numeric" or _is_clean_number(gold):
102
  g, c = _to_float(gold), _to_float(candidate)
103
  if g is not None and c is not None:
104
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
105
  return GradeResult(1.0, "numeric")
 
 
 
 
106
 
107
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
108
  if _math_verify_match(gold, candidate):
109
  return GradeResult(1.0, "math_verify")
110
 
111
  return GradeResult(0.0, "miss")
112
 
113
 
114
- def _tool_calls() -> int | None:
115
- """Number of agent tool calls this rollout, for the efficiency reward.
116
-
117
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
118
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
119
- (efficiency reward becomes null — the harness didn't report a count).
120
- """
121
  try:
122
  with open("/workdir/.n_tool_calls") as fh:
123
  return int(fh.read().strip())
@@ -132,24 +121,17 @@ def _tool_calls() -> int | None:
132
  return None
133
 
134
 
135
- def _tool_efficiency(n_calls: int | None) -> float | None:
136
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
137
-
138
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
139
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
140
- RL reward combiner decides gating/weights.
141
- """
142
- if n_calls is None:
143
  return None
144
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
145
  if budget <= 0:
146
  return None
147
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
148
 
149
 
150
- def _tols() -> tuple[float, float]:
151
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
152
- def _f(name: str) -> float:
153
  try:
154
  return float(os.environ.get(name, "") or 1e-3)
155
  except ValueError:
@@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]:
158
 
159
 
160
  def main_cli() -> int:
161
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
162
-
163
- Inputs (via env vars set by Harbor's [verifier.env]):
164
- EXPECTED_ANSWER — the gold
165
- QUESTION — the original question
166
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
167
-
168
- Predicted answer is read from stdin.
169
- Single float written to stdout. Exit code is always 0.
170
- """
171
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
172
  question = (os.environ.get("QUESTION") or "").strip()
173
  candidate = sys.stdin.read().strip()
174
  at, rt = _tols()
175
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
176
- print(f"{result.reward:.1f}")
177
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
178
- file=sys.stderr)
179
  return 0
180
 
181
 
182
  def main_json() -> int:
183
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
184
-
185
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
186
- correctness — 1.0 iff graded answer matches gold, else 0.0
187
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
188
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
189
-
190
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
191
- """
192
  import json
193
-
194
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
195
  question = (os.environ.get("QUESTION") or "").strip()
196
  candidate = sys.stdin.read().strip()
197
-
198
  if not candidate:
199
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
200
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
201
  return 0
202
-
203
  at, rt = _tols()
204
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
205
- n_calls = _tool_calls()
206
- eff = _tool_efficiency(n_calls)
207
- print(json.dumps({
208
- "correctness": float(result.reward),
209
- "submission": 1.0,
210
- "tool_efficiency": eff,
211
- }))
212
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
213
- f"correctness={result.reward} method={result.method} "
214
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
215
  return 0
216
 
217
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
17
 
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0023_583_23583710_qa_4/tests/grader.py CHANGED
@@ -1,78 +1,34 @@
1
- """Shared three-tier grader.
2
 
3
- Used by both runtimes:
4
- * `env/server.py` — inline inside the `final_answer` ORS @tool method
5
- * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py
6
- and invoked with `python3 /tests/grader.py < /workdir/answer.txt`
7
-
8
- Tiers (cheapest → most expensive):
9
  1. Exact (case-insensitive, whitespace-collapsed)
10
- 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3)
11
- 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt)
12
- — only invoked if OPENAI_API_KEY is set
13
-
14
- CLI form (used by tests/test.sh):
15
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
16
- → reads predicted answer from stdin
17
- → writes a single float ('1.0' or '0.0') to stdout
18
- → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt
19
  """
20
-
21
  from __future__ import annotations
22
-
23
- import os
24
- import re
25
- import sys
26
  from dataclasses import dataclass
27
 
28
-
29
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
30
 
31
- # Locked in PLAN.md §"Locked decisions" — adapted from
32
- # https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py
33
- JUDGE_PROMPT = """You are grading short answers from a data-science agent.
34
- Decide whether the predicted answer is semantically equivalent to the gold answer.
35
-
36
- Rules:
37
- - Case, punctuation, whitespace, articles ("the"), and trailing units don't matter.
38
- - For numbers: predicted must match to the last significant figure of the gold
39
- (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT).
40
- - Extra surrounding prose is fine if the gold value is clearly stated
41
- (gold "5", predicted "There are 5 distinct categories" -> CORRECT).
42
- - Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT).
43
- - Parenthetical annotations in the gold are equivalence hints, not required
44
- (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT;
45
- gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT).
46
- - Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X%
47
- is CORRECT as long as the core numeric value matches
48
- (gold "21.334% in 2014", predicted "21.334" -> CORRECT;
49
- gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch).
50
- - Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one
51
- thing (e.g. "which model?"), predicting either listed value is CORRECT.
52
- - If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED.
53
- - If it commits to a different value -> INCORRECT.
54
-
55
- Question: {question}
56
- Gold answer: {gold}
57
- Predicted answer: {pred}
58
-
59
- Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED)."""
60
-
61
 
62
  @dataclass
63
  class GradeResult:
64
  reward: float
65
- method: str # "exact" | "numeric" | "llm" | "miss"
66
 
67
 
68
  def _normalize(s: str) -> str:
69
  return re.sub(r"\s+", " ", (s or "").strip().lower())
70
 
71
 
72
- def _to_float(s: str) -> float | None:
73
  if not s:
74
  return None
75
- m = _NUMERIC_RE.search(s.replace(",", ""))
76
  if not m:
77
  return None
78
  try:
@@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None:
81
  return None
82
 
83
 
84
- def _math_verify_match(gold: str, candidate: str) -> bool:
85
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
86
-
87
- Catches equivalences the naive float-parse misses: thousands separators,
88
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
89
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
90
- false positive). No network, no LLM.
91
- """
92
- try:
93
- from math_verify import parse, verify
94
-
95
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
96
- except Exception: # noqa: BLE001
97
- return False
98
 
99
 
100
  def _is_clean_number(s: str) -> bool:
101
- """True iff the whole string IS a single number (allowing a leading/trailing
102
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
103
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
104
- the numeric tier must not fire on it (its `_to_float` would grab the leading
105
- '3' and false-positive-match any answer starting with 3)."""
106
  t = (s or "").strip().strip("%$").strip().replace(",", "")
107
  return bool(_NUMERIC_RE.fullmatch(t))
108
 
109
 
110
- def grade(
111
- gold: str,
112
- candidate: str,
113
- *,
114
- question: str = "",
115
- reward_mode: str = "",
116
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
117
- judge_model: str | None = None, # noqa: ARG001
118
- rel_tol: float = 1e-3,
119
- abs_tol: float = 1e-3,
120
- ) -> GradeResult:
121
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
124
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
125
- """
126
 
 
 
127
  if not gold or candidate is None:
128
  return GradeResult(0.0, "miss")
129
 
130
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
131
  if _normalize(gold) == _normalize(candidate):
132
  return GradeResult(1.0, "exact")
133
 
134
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
135
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
136
- # the leading number; those must go to exact/math_verify, which fail closed).
137
- if reward_mode == "numeric" or _is_clean_number(gold):
138
  g, c = _to_float(gold), _to_float(candidate)
139
  if g is not None and c is not None:
140
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
141
  return GradeResult(1.0, "numeric")
 
 
 
 
142
 
143
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
144
  if _math_verify_match(gold, candidate):
145
  return GradeResult(1.0, "math_verify")
146
 
147
  return GradeResult(0.0, "miss")
148
 
149
 
150
- def _tool_calls() -> int | None:
151
- """Number of agent tool calls this rollout, for the efficiency reward.
152
-
153
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
154
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
155
- (efficiency reward becomes null — the harness didn't report a count).
156
- """
157
  try:
158
  with open("/workdir/.n_tool_calls") as fh:
159
  return int(fh.read().strip())
@@ -168,24 +121,17 @@ def _tool_calls() -> int | None:
168
  return None
169
 
170
 
171
- def _tool_efficiency(n_calls: int | None) -> float | None:
172
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
173
-
174
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
175
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
176
- RL reward combiner decides gating/weights.
177
- """
178
- if n_calls is None:
179
  return None
180
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
181
  if budget <= 0:
182
  return None
183
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
184
 
185
 
186
- def _tols() -> tuple[float, float]:
187
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
188
- def _f(name: str) -> float:
189
  try:
190
  return float(os.environ.get(name, "") or 1e-3)
191
  except ValueError:
@@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]:
194
 
195
 
196
  def main_cli() -> int:
197
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
198
-
199
- Inputs (via env vars set by Harbor's [verifier.env]):
200
- EXPECTED_ANSWER — the gold
201
- QUESTION — the original question
202
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
203
-
204
- Predicted answer is read from stdin.
205
- Single float written to stdout. Exit code is always 0.
206
- """
207
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
208
  question = (os.environ.get("QUESTION") or "").strip()
209
  candidate = sys.stdin.read().strip()
210
  at, rt = _tols()
211
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
212
- print(f"{result.reward:.1f}")
213
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
214
- file=sys.stderr)
215
  return 0
216
 
217
 
218
  def main_json() -> int:
219
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
220
-
221
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
222
- correctness — 1.0 iff graded answer matches gold, else 0.0
223
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
224
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
225
-
226
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
227
- """
228
  import json
229
-
230
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
231
  question = (os.environ.get("QUESTION") or "").strip()
232
  candidate = sys.stdin.read().strip()
233
-
234
  if not candidate:
235
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
236
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
237
  return 0
238
-
239
  at, rt = _tols()
240
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
241
- n_calls = _tool_calls()
242
- eff = _tool_efficiency(n_calls)
243
- print(json.dumps({
244
- "correctness": float(result.reward),
245
- "submission": 1.0,
246
- "tool_efficiency": eff,
247
- }))
248
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
249
- f"correctness={result.reward} method={result.method} "
250
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
251
  return 0
252
 
253
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
 
 
 
 
 
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0023_598_23598239_qa_1/tests/grader.py CHANGED
@@ -1,78 +1,34 @@
1
- """Shared three-tier grader.
2
 
3
- Used by both runtimes:
4
- * `env/server.py` — inline inside the `final_answer` ORS @tool method
5
- * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py
6
- and invoked with `python3 /tests/grader.py < /workdir/answer.txt`
7
-
8
- Tiers (cheapest → most expensive):
9
  1. Exact (case-insensitive, whitespace-collapsed)
10
- 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3)
11
- 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt)
12
- — only invoked if OPENAI_API_KEY is set
13
-
14
- CLI form (used by tests/test.sh):
15
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
16
- → reads predicted answer from stdin
17
- → writes a single float ('1.0' or '0.0') to stdout
18
- → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt
19
  """
20
-
21
  from __future__ import annotations
22
-
23
- import os
24
- import re
25
- import sys
26
  from dataclasses import dataclass
27
 
28
-
29
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
30
 
31
- # Locked in PLAN.md §"Locked decisions" — adapted from
32
- # https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py
33
- JUDGE_PROMPT = """You are grading short answers from a data-science agent.
34
- Decide whether the predicted answer is semantically equivalent to the gold answer.
35
-
36
- Rules:
37
- - Case, punctuation, whitespace, articles ("the"), and trailing units don't matter.
38
- - For numbers: predicted must match to the last significant figure of the gold
39
- (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT).
40
- - Extra surrounding prose is fine if the gold value is clearly stated
41
- (gold "5", predicted "There are 5 distinct categories" -> CORRECT).
42
- - Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT).
43
- - Parenthetical annotations in the gold are equivalence hints, not required
44
- (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT;
45
- gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT).
46
- - Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X%
47
- is CORRECT as long as the core numeric value matches
48
- (gold "21.334% in 2014", predicted "21.334" -> CORRECT;
49
- gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch).
50
- - Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one
51
- thing (e.g. "which model?"), predicting either listed value is CORRECT.
52
- - If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED.
53
- - If it commits to a different value -> INCORRECT.
54
-
55
- Question: {question}
56
- Gold answer: {gold}
57
- Predicted answer: {pred}
58
-
59
- Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED)."""
60
-
61
 
62
  @dataclass
63
  class GradeResult:
64
  reward: float
65
- method: str # "exact" | "numeric" | "llm" | "miss"
66
 
67
 
68
  def _normalize(s: str) -> str:
69
  return re.sub(r"\s+", " ", (s or "").strip().lower())
70
 
71
 
72
- def _to_float(s: str) -> float | None:
73
  if not s:
74
  return None
75
- m = _NUMERIC_RE.search(s.replace(",", ""))
76
  if not m:
77
  return None
78
  try:
@@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None:
81
  return None
82
 
83
 
84
- def _math_verify_match(gold: str, candidate: str) -> bool:
85
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
86
-
87
- Catches equivalences the naive float-parse misses: thousands separators,
88
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
89
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
90
- false positive). No network, no LLM.
91
- """
92
- try:
93
- from math_verify import parse, verify
94
-
95
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
96
- except Exception: # noqa: BLE001
97
- return False
98
 
99
 
100
  def _is_clean_number(s: str) -> bool:
101
- """True iff the whole string IS a single number (allowing a leading/trailing
102
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
103
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
104
- the numeric tier must not fire on it (its `_to_float` would grab the leading
105
- '3' and false-positive-match any answer starting with 3)."""
106
  t = (s or "").strip().strip("%$").strip().replace(",", "")
107
  return bool(_NUMERIC_RE.fullmatch(t))
108
 
109
 
110
- def grade(
111
- gold: str,
112
- candidate: str,
113
- *,
114
- question: str = "",
115
- reward_mode: str = "",
116
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
117
- judge_model: str | None = None, # noqa: ARG001
118
- rel_tol: float = 1e-3,
119
- abs_tol: float = 1e-3,
120
- ) -> GradeResult:
121
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
124
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
125
- """
126
 
 
 
127
  if not gold or candidate is None:
128
  return GradeResult(0.0, "miss")
129
 
130
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
131
  if _normalize(gold) == _normalize(candidate):
132
  return GradeResult(1.0, "exact")
133
 
134
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
135
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
136
- # the leading number; those must go to exact/math_verify, which fail closed).
137
- if reward_mode == "numeric" or _is_clean_number(gold):
138
  g, c = _to_float(gold), _to_float(candidate)
139
  if g is not None and c is not None:
140
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
141
  return GradeResult(1.0, "numeric")
 
 
 
 
142
 
143
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
144
  if _math_verify_match(gold, candidate):
145
  return GradeResult(1.0, "math_verify")
146
 
147
  return GradeResult(0.0, "miss")
148
 
149
 
150
- def _tool_calls() -> int | None:
151
- """Number of agent tool calls this rollout, for the efficiency reward.
152
-
153
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
154
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
155
- (efficiency reward becomes null — the harness didn't report a count).
156
- """
157
  try:
158
  with open("/workdir/.n_tool_calls") as fh:
159
  return int(fh.read().strip())
@@ -168,24 +121,17 @@ def _tool_calls() -> int | None:
168
  return None
169
 
170
 
171
- def _tool_efficiency(n_calls: int | None) -> float | None:
172
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
173
-
174
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
175
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
176
- RL reward combiner decides gating/weights.
177
- """
178
- if n_calls is None:
179
  return None
180
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
181
  if budget <= 0:
182
  return None
183
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
184
 
185
 
186
- def _tols() -> tuple[float, float]:
187
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
188
- def _f(name: str) -> float:
189
  try:
190
  return float(os.environ.get(name, "") or 1e-3)
191
  except ValueError:
@@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]:
194
 
195
 
196
  def main_cli() -> int:
197
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
198
-
199
- Inputs (via env vars set by Harbor's [verifier.env]):
200
- EXPECTED_ANSWER — the gold
201
- QUESTION — the original question
202
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
203
-
204
- Predicted answer is read from stdin.
205
- Single float written to stdout. Exit code is always 0.
206
- """
207
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
208
  question = (os.environ.get("QUESTION") or "").strip()
209
  candidate = sys.stdin.read().strip()
210
  at, rt = _tols()
211
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
212
- print(f"{result.reward:.1f}")
213
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
214
- file=sys.stderr)
215
  return 0
216
 
217
 
218
  def main_json() -> int:
219
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
220
-
221
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
222
- correctness — 1.0 iff graded answer matches gold, else 0.0
223
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
224
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
225
-
226
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
227
- """
228
  import json
229
-
230
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
231
  question = (os.environ.get("QUESTION") or "").strip()
232
  candidate = sys.stdin.read().strip()
233
-
234
  if not candidate:
235
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
236
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
237
  return 0
238
-
239
  at, rt = _tols()
240
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
241
- n_calls = _tool_calls()
242
- eff = _tool_efficiency(n_calls)
243
- print(json.dumps({
244
- "correctness": float(result.reward),
245
- "submission": 1.0,
246
- "tool_efficiency": eff,
247
- }))
248
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
249
- f"correctness={result.reward} method={result.method} "
250
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
251
  return 0
252
 
253
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
 
 
 
 
 
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0023_931_23931431_qa_1/tests/grader.py CHANGED
@@ -1,42 +1,34 @@
1
- """Deterministic short-answer grader — NO LLM judge.
2
 
3
- Tiers (cheapest -> most expensive), all offline/deterministic:
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
- 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
- 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify)
7
-
8
- CLI form (used by tests/test.sh):
9
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
10
- -> reads predicted answer from stdin
11
- -> writes a single float ('1.0' or '0.0') to stdout
12
  """
13
-
14
  from __future__ import annotations
15
-
16
- import os
17
- import re
18
- import sys
19
  from dataclasses import dataclass
20
 
21
-
22
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
23
 
24
 
25
-
26
  @dataclass
27
  class GradeResult:
28
  reward: float
29
- method: str # "exact" | "numeric" | "llm" | "miss"
30
 
31
 
32
  def _normalize(s: str) -> str:
33
  return re.sub(r"\s+", " ", (s or "").strip().lower())
34
 
35
 
36
- def _to_float(s: str) -> float | None:
37
  if not s:
38
  return None
39
- m = _NUMERIC_RE.search(s.replace(",", ""))
40
  if not m:
41
  return None
42
  try:
@@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None:
45
  return None
46
 
47
 
48
- def _math_verify_match(gold: str, candidate: str) -> bool:
49
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
50
-
51
- Catches equivalences the naive float-parse misses: thousands separators,
52
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
53
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
54
- false positive). No network, no LLM.
55
- """
56
- try:
57
- from math_verify import parse, verify
58
-
59
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
60
- except Exception: # noqa: BLE001
61
- return False
62
 
63
 
64
  def _is_clean_number(s: str) -> bool:
65
- """True iff the whole string IS a single number (allowing a leading/trailing
66
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
67
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
68
- the numeric tier must not fire on it (its `_to_float` would grab the leading
69
- '3' and false-positive-match any answer starting with 3)."""
70
  t = (s or "").strip().strip("%$").strip().replace(",", "")
71
  return bool(_NUMERIC_RE.fullmatch(t))
72
 
73
 
74
- def grade(
75
- gold: str,
76
- candidate: str,
77
- *,
78
- question: str = "",
79
- reward_mode: str = "",
80
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
81
- judge_model: str | None = None, # noqa: ARG001
82
- rel_tol: float = 1e-3,
83
- abs_tol: float = 1e-3,
84
- ) -> GradeResult:
85
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
88
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
89
- """
90
 
 
 
91
  if not gold or candidate is None:
92
  return GradeResult(0.0, "miss")
93
 
94
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
95
  if _normalize(gold) == _normalize(candidate):
96
  return GradeResult(1.0, "exact")
97
 
98
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
99
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
100
- # the leading number; those must go to exact/math_verify, which fail closed).
101
- if reward_mode == "numeric" or _is_clean_number(gold):
102
  g, c = _to_float(gold), _to_float(candidate)
103
  if g is not None and c is not None:
104
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
105
  return GradeResult(1.0, "numeric")
 
 
 
 
106
 
107
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
108
  if _math_verify_match(gold, candidate):
109
  return GradeResult(1.0, "math_verify")
110
 
111
  return GradeResult(0.0, "miss")
112
 
113
 
114
- def _tool_calls() -> int | None:
115
- """Number of agent tool calls this rollout, for the efficiency reward.
116
-
117
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
118
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
119
- (efficiency reward becomes null — the harness didn't report a count).
120
- """
121
  try:
122
  with open("/workdir/.n_tool_calls") as fh:
123
  return int(fh.read().strip())
@@ -132,24 +121,17 @@ def _tool_calls() -> int | None:
132
  return None
133
 
134
 
135
- def _tool_efficiency(n_calls: int | None) -> float | None:
136
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
137
-
138
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
139
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
140
- RL reward combiner decides gating/weights.
141
- """
142
- if n_calls is None:
143
  return None
144
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
145
  if budget <= 0:
146
  return None
147
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
148
 
149
 
150
- def _tols() -> tuple[float, float]:
151
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
152
- def _f(name: str) -> float:
153
  try:
154
  return float(os.environ.get(name, "") or 1e-3)
155
  except ValueError:
@@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]:
158
 
159
 
160
  def main_cli() -> int:
161
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
162
-
163
- Inputs (via env vars set by Harbor's [verifier.env]):
164
- EXPECTED_ANSWER — the gold
165
- QUESTION — the original question
166
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
167
-
168
- Predicted answer is read from stdin.
169
- Single float written to stdout. Exit code is always 0.
170
- """
171
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
172
  question = (os.environ.get("QUESTION") or "").strip()
173
  candidate = sys.stdin.read().strip()
174
  at, rt = _tols()
175
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
176
- print(f"{result.reward:.1f}")
177
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
178
- file=sys.stderr)
179
  return 0
180
 
181
 
182
  def main_json() -> int:
183
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
184
-
185
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
186
- correctness — 1.0 iff graded answer matches gold, else 0.0
187
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
188
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
189
-
190
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
191
- """
192
  import json
193
-
194
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
195
  question = (os.environ.get("QUESTION") or "").strip()
196
  candidate = sys.stdin.read().strip()
197
-
198
  if not candidate:
199
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
200
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
201
  return 0
202
-
203
  at, rt = _tols()
204
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
205
- n_calls = _tool_calls()
206
- eff = _tool_efficiency(n_calls)
207
- print(json.dumps({
208
- "correctness": float(result.reward),
209
- "submission": 1.0,
210
- "tool_efficiency": eff,
211
- }))
212
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
213
- f"correctness={result.reward} method={result.method} "
214
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
215
  return 0
216
 
217
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
17
 
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0024_069_24069916_qa_1/tests/grader.py CHANGED
@@ -1,42 +1,34 @@
1
- """Deterministic short-answer grader — NO LLM judge.
2
 
3
- Tiers (cheapest -> most expensive), all offline/deterministic:
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
- 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
- 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify)
7
-
8
- CLI form (used by tests/test.sh):
9
- EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py
10
- -> reads predicted answer from stdin
11
- -> writes a single float ('1.0' or '0.0') to stdout
12
  """
13
-
14
  from __future__ import annotations
15
-
16
- import os
17
- import re
18
- import sys
19
  from dataclasses import dataclass
20
 
21
-
22
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
23
 
24
 
25
-
26
  @dataclass
27
  class GradeResult:
28
  reward: float
29
- method: str # "exact" | "numeric" | "llm" | "miss"
30
 
31
 
32
  def _normalize(s: str) -> str:
33
  return re.sub(r"\s+", " ", (s or "").strip().lower())
34
 
35
 
36
- def _to_float(s: str) -> float | None:
37
  if not s:
38
  return None
39
- m = _NUMERIC_RE.search(s.replace(",", ""))
40
  if not m:
41
  return None
42
  try:
@@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None:
45
  return None
46
 
47
 
48
- def _math_verify_match(gold: str, candidate: str) -> bool:
49
- """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify.
50
-
51
- Catches equivalences the naive float-parse misses: thousands separators,
52
- fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms.
53
- Fails CLOSED — any parse error / prose gold / timeout returns False (never a
54
- false positive). No network, no LLM.
55
- """
56
- try:
57
- from math_verify import parse, verify
58
-
59
- return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
60
- except Exception: # noqa: BLE001
61
- return False
62
 
63
 
64
  def _is_clean_number(s: str) -> bool:
65
- """True iff the whole string IS a single number (allowing a leading/trailing
66
- %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'.
67
- A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so
68
- the numeric tier must not fire on it (its `_to_float` would grab the leading
69
- '3' and false-positive-match any answer starting with 3)."""
70
  t = (s or "").strip().strip("%$").strip().replace(",", "")
71
  return bool(_NUMERIC_RE.fullmatch(t))
72
 
73
 
74
- def grade(
75
- gold: str,
76
- candidate: str,
77
- *,
78
- question: str = "",
79
- reward_mode: str = "",
80
- judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed
81
- judge_model: str | None = None, # noqa: ARG001
82
- rel_tol: float = 1e-3,
83
- abs_tol: float = 1e-3,
84
- ) -> GradeResult:
85
- """Deterministic three-tier match — NO LLM judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
- exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify
88
- -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed).
89
- """
90
 
 
 
91
  if not gold or candidate is None:
92
  return GradeResult(0.0, "miss")
93
 
94
- # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ─────────
95
  if _normalize(gold) == _normalize(candidate):
96
  return GradeResult(1.0, "exact")
97
 
98
- # ── Tier 2: numeric — ONLY when the gold is a single clean number ──
99
- # (compound golds like "Y=3 with 95,293 instances" would otherwise match on
100
- # the leading number; those must go to exact/math_verify, which fail closed).
101
- if reward_mode == "numeric" or _is_clean_number(gold):
102
  g, c = _to_float(gold), _to_float(candidate)
103
  if g is not None and c is not None:
104
- if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol:
105
  return GradeResult(1.0, "numeric")
 
 
 
 
106
 
107
- # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ──
 
 
 
 
 
108
  if _math_verify_match(gold, candidate):
109
  return GradeResult(1.0, "math_verify")
110
 
111
  return GradeResult(0.0, "miss")
112
 
113
 
114
- def _tool_calls() -> int | None:
115
- """Number of agent tool calls this rollout, for the efficiency reward.
116
-
117
- Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls
118
- back to the `N_TOOL_CALLS` env var. Returns None if neither is present
119
- (efficiency reward becomes null — the harness didn't report a count).
120
- """
121
  try:
122
  with open("/workdir/.n_tool_calls") as fh:
123
  return int(fh.read().strip())
@@ -132,24 +121,17 @@ def _tool_calls() -> int | None:
132
  return None
133
 
134
 
135
- def _tool_efficiency(n_calls: int | None) -> float | None:
136
- """0..1 efficiency signal: fewer tool calls -> higher. None if unknown.
137
-
138
- clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B
139
- median was ~9-10 calls). Raw signal — NOT gated on correctness here; the
140
- RL reward combiner decides gating/weights.
141
- """
142
- if n_calls is None:
143
  return None
144
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
145
  if budget <= 0:
146
  return None
147
- return max(0.0, min(1.0, 1.0 - n_calls / budget))
148
 
149
 
150
- def _tols() -> tuple[float, float]:
151
- """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default."""
152
- def _f(name: str) -> float:
153
  try:
154
  return float(os.environ.get(name, "") or 1e-3)
155
  except ValueError:
@@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]:
158
 
159
 
160
  def main_cli() -> int:
161
- """CLI shim for `tests/test.sh` — env-driven, stdout-only.
162
-
163
- Inputs (via env vars set by Harbor's [verifier.env]):
164
- EXPECTED_ANSWER — the gold
165
- QUESTION — the original question
166
- ATOL / RTOL — per-task numeric tolerances (default 1e-3)
167
-
168
- Predicted answer is read from stdin.
169
- Single float written to stdout. Exit code is always 0.
170
- """
171
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
172
  question = (os.environ.get("QUESTION") or "").strip()
173
  candidate = sys.stdin.read().strip()
174
  at, rt = _tols()
175
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
176
- print(f"{result.reward:.1f}")
177
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}",
178
- file=sys.stderr)
179
  return 0
180
 
181
 
182
  def main_json() -> int:
183
- """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict.
184
-
185
- Three named rewards (Harbor's VerifierResult.rewards carries them all):
186
- correctness — 1.0 iff graded answer matches gold, else 0.0
187
- submission — 1.0 iff a non-empty answer was submitted, else 0.0
188
- tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown
189
-
190
- No submission -> all three 0. Predicted answer on stdin; JSON to stdout.
191
- """
192
  import json
193
-
194
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
195
  question = (os.environ.get("QUESTION") or "").strip()
196
  candidate = sys.stdin.read().strip()
197
-
198
  if not candidate:
199
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
200
- print("[grader] no submission -> all rewards 0", file=sys.stderr)
201
  return 0
202
-
203
  at, rt = _tols()
204
- result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt)
205
- n_calls = _tool_calls()
206
- eff = _tool_efficiency(n_calls)
207
- print(json.dumps({
208
- "correctness": float(result.reward),
209
- "submission": 1.0,
210
- "tool_efficiency": eff,
211
- }))
212
- print(f"[grader] gold={gold!r} pred={candidate[:80]!r} "
213
- f"correctness={result.reward} method={result.method} "
214
- f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr)
215
  return 0
216
 
217
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
 
3
+ Tiers (all offline/deterministic):
4
  1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
 
 
10
  """
 
11
  from __future__ import annotations
12
+ import os, re, sys
 
 
 
13
  from dataclasses import dataclass
14
 
 
15
  _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
 
17
 
 
18
  @dataclass
19
  class GradeResult:
20
  reward: float
21
+ method: str
22
 
23
 
24
  def _normalize(s: str) -> str:
25
  return re.sub(r"\s+", " ", (s or "").strip().lower())
26
 
27
 
28
+ def _to_float(s: str):
29
  if not s:
30
  return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
  if not m:
33
  return None
34
  try:
 
37
  return None
38
 
39
 
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
 
44
  def _is_clean_number(s: str) -> bool:
 
 
 
 
 
45
  t = (s or "").strip().strip("%$").strip().replace(",", "")
46
  return bool(_NUMERIC_RE.fullmatch(t))
47
 
48
 
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
 
 
 
 
76
 
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
  if not gold or candidate is None:
80
  return GradeResult(0.0, "miss")
81
 
82
+ # Tier 1: exact
83
  if _normalize(gold) == _normalize(candidate):
84
  return GradeResult(1.0, "exact")
85
 
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
 
 
88
  g, c = _to_float(gold), _to_float(candidate)
89
  if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
  return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
 
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
  if _math_verify_match(gold, candidate):
104
  return GradeResult(1.0, "math_verify")
105
 
106
  return GradeResult(0.0, "miss")
107
 
108
 
109
+ def _tool_calls():
 
 
 
 
 
 
110
  try:
111
  with open("/workdir/.n_tool_calls") as fh:
112
  return int(fh.read().strip())
 
121
  return None
122
 
123
 
124
+ def _tool_efficiency(n):
125
+ if n is None:
 
 
 
 
 
 
126
  return None
127
  budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
  if budget <= 0:
129
  return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
 
132
 
133
+ def _tols():
134
+ def _f(name):
 
135
  try:
136
  return float(os.environ.get(name, "") or 1e-3)
137
  except ValueError:
 
140
 
141
 
142
  def main_cli() -> int:
 
 
 
 
 
 
 
 
 
 
143
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
  question = (os.environ.get("QUESTION") or "").strip()
145
  candidate = sys.stdin.read().strip()
146
  at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
 
150
  return 0
151
 
152
 
153
  def main_json() -> int:
 
 
 
 
 
 
 
 
 
154
  import json
 
155
  gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
  question = (os.environ.get("QUESTION") or "").strip()
157
  candidate = sys.stdin.read().strip()
 
158
  if not candidate:
159
  print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
 
160
  return 0
 
161
  at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
 
 
 
 
 
 
 
166
  return 0
167
 
168
 
tasks/0024_275_24275657_qa_5/environment/Dockerfile ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ FROM docker.io/savatar101/env-data-agent-train:base
2
+ WORKDIR /workdir
tasks/0024_275_24275657_qa_5/environment/pull_bucket.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pull this task's bucket prefix into /home/user/input/.
2
+
3
+ Invoked by Harbor's [environment.healthcheck] command (declared in task.toml)
4
+ — runs after container start, before the agent. Idempotent: skips work if
5
+ files are already present from a prior pull.
6
+ """
7
+
8
+ import os
9
+ import sys
10
+ from pathlib import Path
11
+
12
+ from huggingface_hub import download_bucket_files, list_bucket_tree
13
+
14
+
15
+ def main() -> int:
16
+ bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all"
17
+ prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/"
18
+ dest = Path("/home/user/input")
19
+ dest.mkdir(parents=True, exist_ok=True)
20
+
21
+ existing = [p for p in dest.iterdir() if p.is_file()]
22
+ if existing:
23
+ print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True)
24
+ return 0
25
+
26
+ targets = [
27
+ (it.path, str(dest / Path(it.path).name))
28
+ for it in list_bucket_tree(bucket, prefix=prefix, recursive=True)
29
+ if getattr(it, "type", None) == "file"
30
+ ]
31
+ if not targets:
32
+ print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True)
33
+ return 2
34
+
35
+ download_bucket_files(bucket, files=targets)
36
+ print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True)
37
+ return 0
38
+
39
+
40
+ if __name__ == "__main__":
41
+ sys.exit(main())
tasks/0024_275_24275657_qa_5/tests/grader.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deterministic short-answer grader v2 — NO LLM judge.
2
+
3
+ Tiers (all offline/deterministic):
4
+ 1. Exact (case-insensitive, whitespace-collapsed)
5
+ 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds)
6
+ + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621)
7
+ 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element
8
+ (fixes 'a, b' vs 'a,b' spacing and reordering)
9
+ 4. Math-Verify (symbolic/numeric equivalence)
10
+ """
11
+ from __future__ import annotations
12
+ import os, re, sys
13
+ from dataclasses import dataclass
14
+
15
+ _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
16
+
17
+
18
+ @dataclass
19
+ class GradeResult:
20
+ reward: float
21
+ method: str
22
+
23
+
24
+ def _normalize(s: str) -> str:
25
+ return re.sub(r"\s+", " ", (s or "").strip().lower())
26
+
27
+
28
+ def _to_float(s: str):
29
+ if not s:
30
+ return None
31
+ m = _NUMERIC_RE.search(str(s).replace(",", ""))
32
+ if not m:
33
+ return None
34
+ try:
35
+ return float(m.group(0))
36
+ except ValueError:
37
+ return None
38
+
39
+
40
+ def _num_close(g, c, abs_tol, rel_tol) -> bool:
41
+ return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol
42
+
43
+
44
+ def _is_clean_number(s: str) -> bool:
45
+ t = (s or "").strip().strip("%$").strip().replace(",", "")
46
+ return bool(_NUMERIC_RE.fullmatch(t))
47
+
48
+
49
+ def _elem_match(a, b, abs_tol, rel_tol) -> bool:
50
+ if _normalize(a) == _normalize(b):
51
+ return True
52
+ fa, fb = _to_float(a), _to_float(b)
53
+ if fa is not None and fb is not None:
54
+ return _num_close(fa, fb, abs_tol, rel_tol)
55
+ return False
56
+
57
+
58
+ def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool:
59
+ gl = [x.strip() for x in gold.split(",") if x.strip()]
60
+ cl = [x.strip() for x in cand.split(",") if x.strip()]
61
+ if len(gl) < 2 or len(gl) != len(cl):
62
+ return False
63
+ for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))):
64
+ if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _math_verify_match(gold: str, candidate: str) -> bool:
70
+ try:
71
+ from math_verify import parse, verify
72
+ return bool(verify(parse(gold), parse(candidate), timeout_seconds=5))
73
+ except Exception:
74
+ return False
75
+
76
+
77
+ def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "",
78
+ judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult:
79
+ if not gold or candidate is None:
80
+ return GradeResult(0.0, "miss")
81
+
82
+ # Tier 1: exact
83
+ if _normalize(gold) == _normalize(candidate):
84
+ return GradeResult(1.0, "exact")
85
+
86
+ # Tier 2: numeric (clean-number gold) + percent/fraction bridge
87
+ if reward_mode in ("numeric", "flexible") or _is_clean_number(gold):
88
+ g, c = _to_float(gold), _to_float(candidate)
89
+ if g is not None and c is not None:
90
+ if _num_close(g, c, abs_tol, rel_tol):
91
+ return GradeResult(1.0, "numeric")
92
+ # percent<->fraction: one side is a fraction (<1), the other a percent (>=1)
93
+ if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)):
94
+ if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol):
95
+ return GradeResult(1.0, "numeric_scaled")
96
+
97
+ # Tier 3: list (comma-separated), order-insensitive, per-element tolerant
98
+ if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate):
99
+ if _list_match(gold, candidate, abs_tol, rel_tol):
100
+ return GradeResult(1.0, "list")
101
+
102
+ # Tier 4: math-verify
103
+ if _math_verify_match(gold, candidate):
104
+ return GradeResult(1.0, "math_verify")
105
+
106
+ return GradeResult(0.0, "miss")
107
+
108
+
109
+ def _tool_calls():
110
+ try:
111
+ with open("/workdir/.n_tool_calls") as fh:
112
+ return int(fh.read().strip())
113
+ except (OSError, ValueError):
114
+ pass
115
+ raw = os.environ.get("N_TOOL_CALLS")
116
+ if raw is not None:
117
+ try:
118
+ return int(str(raw).strip())
119
+ except ValueError:
120
+ return None
121
+ return None
122
+
123
+
124
+ def _tool_efficiency(n):
125
+ if n is None:
126
+ return None
127
+ budget = float(os.environ.get("TOOL_BUDGET", "15") or "15")
128
+ if budget <= 0:
129
+ return None
130
+ return max(0.0, min(1.0, 1.0 - n / budget))
131
+
132
+
133
+ def _tols():
134
+ def _f(name):
135
+ try:
136
+ return float(os.environ.get(name, "") or 1e-3)
137
+ except ValueError:
138
+ return 1e-3
139
+ return _f("ATOL"), _f("RTOL")
140
+
141
+
142
+ def main_cli() -> int:
143
+ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
144
+ question = (os.environ.get("QUESTION") or "").strip()
145
+ candidate = sys.stdin.read().strip()
146
+ at, rt = _tols()
147
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
148
+ print(f"{r.reward:.1f}")
149
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr)
150
+ return 0
151
+
152
+
153
+ def main_json() -> int:
154
+ import json
155
+ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip()
156
+ question = (os.environ.get("QUESTION") or "").strip()
157
+ candidate = sys.stdin.read().strip()
158
+ if not candidate:
159
+ print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0}))
160
+ return 0
161
+ at, rt = _tols()
162
+ r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt)
163
+ n = _tool_calls()
164
+ print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)}))
165
+ print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr)
166
+ return 0
167
+
168
+
169
+ if __name__ == "__main__":
170
+ if "--json" in sys.argv[1:]:
171
+ raise SystemExit(main_json())
172
+ raise SystemExit(main_cli())