Jainamshahhh commited on
Commit
b2941bb
·
verified ·
1 Parent(s): 94778df

Upload common/exec_gate.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. common/exec_gate.py +116 -0
common/exec_gate.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Parallel row-validation harness, shared by every entry.
2
+
3
+ Generalized from chartforge/render_check.py, whose ProcessPoolExecutor driver was always
4
+ generic while only its inner check was chart-specific.
5
+
6
+ THE RULE THIS MODULE EXISTS TO ENFORCE: **the gate imports the released scorer**, it does
7
+ not reimplement it. If the scorer's semantics change, the gate changes with it, so a row
8
+ can never pass generation-time validation and then fail evaluation-time scoring. Every
9
+ entry passes its own `check_fn`, and every `check_fn` must call into that entry's real
10
+ scorer rather than a lookalike.
11
+
12
+ A `check_fn` takes whatever tuple the entry finds convenient, whose first element is the
13
+ row id, and returns `(row_id, ok, reason)`. Reasons are formatted `"bucket: detail"` so
14
+ `drop_reasons()` aggregates them for free.
15
+
16
+ from common.exec_gate import check_many, drop_reasons
17
+ verdicts = check_many(items, my_check, workers=8)
18
+ kept = [i for i in items if verdicts[i[0]][0]]
19
+ print(drop_reasons(verdicts))
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import json
24
+ import subprocess
25
+ import sys
26
+ import tempfile
27
+ from collections import Counter
28
+ from concurrent.futures import ProcessPoolExecutor, as_completed
29
+ from pathlib import Path
30
+ from typing import Callable, Sequence
31
+
32
+ TIMEOUT_S = 8
33
+
34
+ CheckFn = Callable[[tuple], tuple[str, bool, str]]
35
+
36
+
37
+ def check_many(items: Sequence[tuple], check_fn: CheckFn, workers: int = 8,
38
+ progress_every: int = 2000) -> dict[str, tuple[bool, str]]:
39
+ """Validate rows in parallel. Execution is CPU-bound, so processes beat threads.
40
+
41
+ check_fn must be a module-level function (picklable), not a lambda or closure.
42
+ """
43
+ results: dict[str, tuple[bool, str]] = {}
44
+ with ProcessPoolExecutor(max_workers=workers) as pool:
45
+ futs = {pool.submit(check_fn, it): it[0] for it in items}
46
+ done = 0
47
+ for fut in as_completed(futs):
48
+ rid, ok, why = fut.result()
49
+ results[rid] = (ok, why)
50
+ done += 1
51
+ if progress_every and done % progress_every == 0:
52
+ kept = sum(1 for v in results.values() if v[0])
53
+ print(f" checked {done}/{len(items)} kept {kept}", flush=True)
54
+ return results
55
+
56
+
57
+ def drop_reasons(verdicts: dict[str, tuple[bool, str]]) -> dict[str, int]:
58
+ """Aggregate failures by the bucket prefix before the first colon."""
59
+ return dict(Counter(why.split(":")[0] for ok, why in verdicts.values() if not ok
60
+ ).most_common())
61
+
62
+
63
+ def run_python(code: str, marker: str = "__RESULT__", timeout: int = TIMEOUT_S,
64
+ preamble: str = "") -> object | None:
65
+ """Execute code in a subprocess and return the JSON printed after `marker`.
66
+
67
+ Used by entries that score by executing generated code. The subprocess is the
68
+ isolation boundary: a row that hangs or segfaults costs one worker, not the run.
69
+ """
70
+ script = (preamble + "\n" + code) if preamble else code
71
+ path = None
72
+ try:
73
+ with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False) as f:
74
+ f.write(script)
75
+ path = f.name
76
+ out = subprocess.run([sys.executable, path], capture_output=True,
77
+ text=True, timeout=timeout)
78
+ for line in out.stdout.splitlines():
79
+ if line.startswith(marker):
80
+ return json.loads(line[len(marker):])
81
+ return None
82
+ except Exception:
83
+ return None
84
+ finally:
85
+ if path:
86
+ try:
87
+ Path(path).unlink(missing_ok=True)
88
+ except Exception:
89
+ pass
90
+
91
+
92
+ def _echo_check(item: tuple) -> tuple[str, bool, str]:
93
+ """Module-level so the selftest can pickle it."""
94
+ rid, value = item
95
+ if value < 0:
96
+ return rid, False, "negative: value below zero"
97
+ if value == 0:
98
+ return rid, False, "zero: value is zero"
99
+ return rid, True, "ok"
100
+
101
+
102
+ def _selftest() -> None:
103
+ items = [("a", 1), ("b", -1), ("c", 0), ("d", 5), ("e", -2)]
104
+ v = check_many(items, _echo_check, workers=2, progress_every=0)
105
+ assert len(v) == 5
106
+ assert [k for k in v if v[k][0]] == ["a", "d"] or set(k for k in v if v[k][0]) == {"a", "d"}
107
+ assert drop_reasons(v) == {"negative": 2, "zero": 1}, drop_reasons(v)
108
+
109
+ assert run_python('print("__RESULT__" + __import__("json").dumps([1,2]))') == [1, 2]
110
+ assert run_python('raise SystemExit(1)') is None
111
+ assert run_python('import time; time.sleep(30)', timeout=2) is None
112
+ print("exec_gate selftest: 5/5 OK")
113
+
114
+
115
+ if __name__ == "__main__":
116
+ _selftest()