Kevin589981 commited on
Commit
08becbd
·
verified ·
1 Parent(s): 02dbac0

document beginner evaluation workflow and result summaries (part 2)

Browse files
tools/materialize.py CHANGED
@@ -20,6 +20,32 @@ def normalize_task_id(value: str) -> str:
20
  return f"{int(raw):03d}"
21
 
22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  def load_rows() -> list[dict[str, object]]:
24
  return [json.loads(line) for line in (ROOT / "manifests" / "tasks.jsonl").read_text(encoding="utf-8").splitlines() if line.strip()]
25
 
@@ -37,8 +63,14 @@ def task_source(task_path: str, *, root: Path = ROOT) -> Path:
37
  def main() -> int:
38
  parser = argparse.ArgumentParser(description=__doc__)
39
  parser.add_argument("--output", type=Path, default=ROOT / "tasks-selected")
40
- parser.add_argument("--task-id", action="append", dest="task_ids")
41
- parser.add_argument("--allow-GPL", action="store_true", dest="allow_gpl")
 
 
 
 
 
 
42
  parser.add_argument(
43
  "--include-build-context",
44
  action="store_true",
@@ -46,15 +78,23 @@ def main() -> int:
46
  )
47
  parser.add_argument("--force", action="store_true")
48
  args = parser.parse_args()
49
- selected = {normalize_task_id(value) for value in args.task_ids} if args.task_ids else None
50
- rows = []
51
- for row in load_rows():
52
- task_id = str(row["release_id"])
53
- if selected is not None and task_id not in selected:
54
- continue
55
- if bool(row.get("gpl_family")) and not args.allow_gpl:
56
- continue
57
- rows.append(row)
 
 
 
 
 
 
 
 
58
  if args.output.exists():
59
  if not args.force:
60
  raise FileExistsError(f"output exists; use --force: {args.output}")
 
20
  return f"{int(raw):03d}"
21
 
22
 
23
+ def expand_task_selectors(values: list[str] | None) -> set[str] | None:
24
+ """Expand repeated, comma-separated ids and inclusive id ranges."""
25
+ if not values:
26
+ return None
27
+ selected: set[str] = set()
28
+ for value in values:
29
+ for selector in value.split(","):
30
+ selector = selector.strip()
31
+ if not selector:
32
+ continue
33
+ if "-" not in selector:
34
+ selected.add(normalize_task_id(selector))
35
+ continue
36
+ pieces = [piece.strip() for piece in selector.split("-")]
37
+ if len(pieces) != 2 or not all(pieces):
38
+ raise ValueError(f"invalid task range: {selector!r}")
39
+ start = int(normalize_task_id(pieces[0]))
40
+ end = int(normalize_task_id(pieces[1]))
41
+ if start > end:
42
+ raise ValueError(f"task range must be ascending: {selector!r}")
43
+ selected.update(f"{task_id:03d}" for task_id in range(start, end + 1))
44
+ if not selected:
45
+ raise ValueError("at least one task id is required")
46
+ return selected
47
+
48
+
49
  def load_rows() -> list[dict[str, object]]:
50
  return [json.loads(line) for line in (ROOT / "manifests" / "tasks.jsonl").read_text(encoding="utf-8").splitlines() if line.strip()]
51
 
 
63
  def main() -> int:
64
  parser = argparse.ArgumentParser(description=__doc__)
65
  parser.add_argument("--output", type=Path, default=ROOT / "tasks-selected")
66
+ parser.add_argument(
67
+ "--task-id", action="append", dest="task_ids",
68
+ help="Task id selector; repeat or use commas/ranges, e.g. 002,005-007",
69
+ )
70
+ parser.add_argument(
71
+ "--allow-GPL", "--allow-gpl", action="store_true", dest="allow_gpl",
72
+ help="Allow the 12 GPL-family tasks in the materialized selection",
73
+ )
74
  parser.add_argument(
75
  "--include-build-context",
76
  action="store_true",
 
78
  )
79
  parser.add_argument("--force", action="store_true")
80
  args = parser.parse_args()
81
+ selected = expand_task_selectors(args.task_ids)
82
+ available_rows = load_rows()
83
+ available_ids = {str(row["release_id"]) for row in available_rows}
84
+ if selected is not None:
85
+ unknown = selected - available_ids
86
+ if unknown:
87
+ raise ValueError(f"unknown task ids: {', '.join(sorted(unknown))}")
88
+ matched = [
89
+ row for row in available_rows
90
+ if selected is None or str(row["release_id"]) in selected
91
+ ]
92
+ gated = [str(row["release_id"]) for row in matched if bool(row.get("gpl_family"))]
93
+ if gated and not args.allow_gpl:
94
+ raise ValueError(
95
+ "GPL-family task selection requires --allow-GPL: " + ", ".join(gated)
96
+ )
97
+ rows = [row for row in matched if args.allow_gpl or not bool(row.get("gpl_family"))]
98
  if args.output.exists():
99
  if not args.force:
100
  raise FileExistsError(f"output exists; use --force: {args.output}")
tools/run_batch.py CHANGED
@@ -17,6 +17,11 @@ try:
17
  except ImportError: # Direct execution: python3 scripts/run_batch.py
18
  from provider_config import parse_dotenv, render_codex_config, resolve_codex_profile
19
 
 
 
 
 
 
20
  try:
21
  import tomllib
22
  except ModuleNotFoundError: # Python 3.10 and earlier
@@ -93,11 +98,28 @@ def redacted_command(command: list[str]) -> str:
93
  redacted.extend([value, "config_toml=<provider-config>"])
94
  index += 2
95
  continue
 
 
 
 
 
 
96
  redacted.append(value)
97
  index += 1
98
  return shlex.join(redacted)
99
 
100
 
 
 
 
 
 
 
 
 
 
 
 
101
  def main() -> int:
102
  parser = argparse.ArgumentParser(description=__doc__)
103
  parser.add_argument("--path", type=Path, required=True, help="Materialized task directory")
@@ -205,6 +227,12 @@ def main() -> int:
205
  "selection_sha256": selection["selection_sha256"],
206
  "image_refs": image_refs,
207
  "platform": args.platform,
 
 
 
 
 
 
208
  "pier_command": redacted_command(command),
209
  "agent_import_path": agent_import_path,
210
  "provider": provider_metadata,
@@ -223,7 +251,13 @@ def main() -> int:
223
  pier_environment["PYTHONPATH"] = os.pathsep.join(
224
  value for value in (tool_root, existing_pythonpath) if value
225
  )
226
- return subprocess.run(command, check=False, env=pier_environment).returncode
 
 
 
 
 
 
227
 
228
 
229
  if __name__ == "__main__":
 
17
  except ImportError: # Direct execution: python3 scripts/run_batch.py
18
  from provider_config import parse_dotenv, render_codex_config, resolve_codex_profile
19
 
20
+ try:
21
+ from .summarize_results import write_summary
22
+ except ImportError: # Direct execution: python3 scripts/run_batch.py
23
+ from summarize_results import write_summary
24
+
25
  try:
26
  import tomllib
27
  except ModuleNotFoundError: # Python 3.10 and earlier
 
98
  redacted.extend([value, "config_toml=<provider-config>"])
99
  index += 2
100
  continue
101
+ if "=" in value:
102
+ key = value.split("=", 1)[0].lower()
103
+ if any(marker in key for marker in ("key", "token", "secret", "password", "authorization")):
104
+ redacted.append(key + "=<redacted>")
105
+ index += 1
106
+ continue
107
  redacted.append(value)
108
  index += 1
109
  return shlex.join(redacted)
110
 
111
 
112
+ def pier_version(pier_bin: str) -> str | None:
113
+ try:
114
+ completed = subprocess.run(
115
+ [pier_bin, "--version"], capture_output=True, text=True, check=False
116
+ )
117
+ except OSError:
118
+ return None
119
+ value = (completed.stdout or completed.stderr).strip()
120
+ return value or None
121
+
122
+
123
  def main() -> int:
124
  parser = argparse.ArgumentParser(description=__doc__)
125
  parser.add_argument("--path", type=Path, required=True, help="Materialized task directory")
 
227
  "selection_sha256": selection["selection_sha256"],
228
  "image_refs": image_refs,
229
  "platform": args.platform,
230
+ "agent": args.agent,
231
+ "models": models,
232
+ "n_concurrent": args.n_concurrent,
233
+ "n_attempts": args.n_attempts,
234
+ "max_retries": args.max_retries,
235
+ "pier_version": pier_version(args.pier_bin),
236
  "pier_command": redacted_command(command),
237
  "agent_import_path": agent_import_path,
238
  "provider": provider_metadata,
 
251
  pier_environment["PYTHONPATH"] = os.pathsep.join(
252
  value for value in (tool_root, existing_pythonpath) if value
253
  )
254
+ returncode = subprocess.run(command, check=False, env=pier_environment).returncode
255
+ try:
256
+ summary_json, summary_csv = write_summary(args.jobs_dir)
257
+ print(json.dumps({"summary_json": str(summary_json), "summary_csv": str(summary_csv)}, indent=2))
258
+ except (OSError, ValueError) as exc:
259
+ print(f"warning: unable to write result summary: {exc}", file=sys.stderr)
260
+ return returncode
261
 
262
 
263
  if __name__ == "__main__":
tools/summarize_results.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Flatten Pier job outputs into a small JSON and CSV evaluation summary."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import csv
8
+ import json
9
+ import re
10
+ from datetime import datetime, timezone
11
+ from pathlib import Path
12
+
13
+
14
+ TRIAL_RE = re.compile(r"^(task_\d{3})__(.+)$")
15
+ FIELDS = (
16
+ "task_id", "trial_id", "reward", "public_passed", "public_collected",
17
+ "private_passed", "private_collected", "failure_class", "verifier_dir",
18
+ )
19
+
20
+
21
+ def _load_json(path: Path) -> dict[str, object]:
22
+ try:
23
+ value = json.loads(path.read_text(encoding="utf-8"))
24
+ except (OSError, json.JSONDecodeError):
25
+ return {}
26
+ return value if isinstance(value, dict) else {}
27
+
28
+
29
+ def _failure_by_trial(job_result: dict[str, object]) -> dict[str, str]:
30
+ output: dict[str, str] = {}
31
+ stats = job_result.get("stats")
32
+ if not isinstance(stats, dict):
33
+ return output
34
+ evaluations = stats.get("evals")
35
+ if not isinstance(evaluations, dict):
36
+ return output
37
+ for evaluation in evaluations.values():
38
+ if not isinstance(evaluation, dict):
39
+ continue
40
+ exceptions = evaluation.get("exception_stats")
41
+ if not isinstance(exceptions, dict):
42
+ continue
43
+ for failure_class, trials in exceptions.items():
44
+ if isinstance(trials, list):
45
+ for trial in trials:
46
+ output[str(trial)] = str(failure_class)
47
+ return output
48
+
49
+
50
+ def collect_rows(jobs_dir: Path) -> list[dict[str, object]]:
51
+ rows: list[dict[str, object]] = []
52
+ for job_dir in sorted(path for path in jobs_dir.iterdir() if path.is_dir()):
53
+ job_result = _load_json(job_dir / "result.json")
54
+ failure_by_trial = _failure_by_trial(job_result)
55
+ for trial_dir in sorted(path for path in job_dir.iterdir() if path.is_dir()):
56
+ match = TRIAL_RE.match(trial_dir.name)
57
+ if not match:
58
+ continue
59
+ reward = _load_json(trial_dir / "verifier" / "reward.json")
60
+ public = reward.get("public") if isinstance(reward.get("public"), dict) else {}
61
+ private = reward.get("private") if isinstance(reward.get("private"), dict) else {}
62
+ rows.append(
63
+ {
64
+ "task_id": match.group(1).removeprefix("task_"),
65
+ "trial_id": trial_dir.name,
66
+ "reward": reward.get("reward", ""),
67
+ "public_passed": public.get("passed", ""),
68
+ "public_collected": public.get("collected", ""),
69
+ "private_passed": private.get("passed", ""),
70
+ "private_collected": private.get("collected", ""),
71
+ "failure_class": failure_by_trial.get(trial_dir.name, ""),
72
+ "verifier_dir": str(trial_dir / "verifier"),
73
+ }
74
+ )
75
+ return rows
76
+
77
+
78
+ def write_summary(jobs_dir: Path, output_dir: Path | None = None) -> tuple[Path, Path]:
79
+ jobs_dir = jobs_dir.resolve()
80
+ output_dir = (output_dir or jobs_dir).resolve()
81
+ output_dir.mkdir(parents=True, exist_ok=True)
82
+ rows = collect_rows(jobs_dir)
83
+ payload = {
84
+ "generated_at": datetime.now(timezone.utc).isoformat(),
85
+ "jobs_dir": str(jobs_dir),
86
+ "trial_count": len(rows),
87
+ "rows": rows,
88
+ }
89
+ json_path = output_dir / "summary.json"
90
+ csv_path = output_dir / "summary.csv"
91
+ json_path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
92
+ with csv_path.open("w", encoding="utf-8", newline="") as handle:
93
+ writer = csv.DictWriter(handle, fieldnames=FIELDS, lineterminator="\n")
94
+ writer.writeheader()
95
+ writer.writerows(rows)
96
+ return json_path, csv_path
97
+
98
+
99
+ def main() -> int:
100
+ parser = argparse.ArgumentParser(description=__doc__)
101
+ parser.add_argument("--jobs-dir", type=Path, default=Path("jobs"))
102
+ parser.add_argument("--output-dir", type=Path)
103
+ args = parser.parse_args()
104
+ json_path, csv_path = write_summary(args.jobs_dir, args.output_dir)
105
+ print(json.dumps({"summary_json": str(json_path), "summary_csv": str(csv_path)}, indent=2))
106
+ return 0
107
+
108
+
109
+ if __name__ == "__main__":
110
+ raise SystemExit(main())