zero-code-l1-val / mbppplus /evaluator.py
Tommysha's picture
Add mbppplus 378, codeforces 408, cc_valid 117 independent val configs
bbc5c85 verified
Raw History Blame Contribute Delete
5.33 kB
#!/usr/bin/env python3
"""Zevo custom evaluator for MBPP+ val (378), pass@1.
Hub: Tommysha/zero-code-l1-val config mbppplus split validation.
Rows: id, prompt, entry_point, test_imports, test_list, test (EvalPlus plus harness).
Does not use the gold `code` column.
Usage: python3 evaluator.py PREDICTIONS_CSV SCORING_SET METRICS_JSON
Stdlib only (pyarrow only if SCORING_SET is parquet). Timeout 10 s per problem.
If numpy is missing, a tiny shim satisfies `import numpy as np` in the plus harness.
"""
import ast
import csv
import json
import multiprocessing
import os
import sys
import traceback
from concurrent.futures import ProcessPoolExecutor
TIMEOUT = 10
def extract_code(output: str) -> str:
lines = (output or "").split("\n")
idx = [i for i, line in enumerate(lines) if "```" in line]
if len(idx) >= 2:
body = "\n".join(lines[idx[-2] + 1: idx[-1]])
if body.lstrip().startswith("python"):
body = "\n".join(body.split("\n")[1:])
return body
return (output or "").strip()
def _numpy_shim():
class _NP:
ndarray = type("ndarray", (), {})
float64 = "float64"
float32 = "float32"
@staticmethod
def allclose(a, b, rtol=1e-07, atol=1e-06, equal_nan=False):
def _flat(x):
if isinstance(x, (list, tuple, set)):
out = []
for i in x:
out.extend(_flat(i))
return out
return [x]
aa, bb = _flat(a), _flat(b)
if len(aa) != len(bb):
return False
for x, y in zip(aa, bb):
try:
xf, yf = float(x), float(y)
except (TypeError, ValueError):
if x != y:
return False
continue
if xf != xf or yf != yf:
if not equal_nan:
return False
continue
scale = max(abs(yf), abs(xf))
if abs(xf - yf) > atol + rtol * scale:
return False
return True
return _NP()
def _run_one(code, test, test_list, test_imports, result):
try:
ns = {}
for imp in test_imports or []:
exec(imp, ns, ns)
exec(code, ns, ns)
plus = (test or "").strip()
if plus:
if "numpy" not in sys.modules:
try:
import numpy # noqa: F401
except Exception:
sys.modules["numpy"] = _numpy_shim()
exec(plus, ns, ns)
else:
for stmt in test_list or []:
exec(stmt, ns, ns)
result.append(True)
except Exception:
result.append(False)
def check(args):
code, test, test_list, test_imports = args
if not (code or "").strip():
return False
try:
ast.parse(code)
except SyntaxError:
return False
manager = multiprocessing.Manager()
result = manager.list()
p = multiprocessing.Process(
target=_run_one, args=(code, test, test_list, test_imports, result)
)
p.start()
p.join(timeout=TIMEOUT + 2)
if p.is_alive():
p.kill()
p.join(1)
return bool(result) and result[0] is True
def load_rows(path):
ext = os.path.splitext(path)[1].lower()
if ext == ".parquet":
import pyarrow.parquet as pq
return pq.read_table(path).to_pylist()
if ext == ".jsonl":
return [json.loads(l) for l in open(path, encoding="utf-8") if l.strip()]
if ext == ".json":
d = json.load(open(path, encoding="utf-8"))
return d if isinstance(d, list) else d.get("data", d.get("rows"))
csv.field_size_limit(sys.maxsize)
return list(csv.DictReader(open(path, newline="", encoding="utf-8")))
def _list_field(v):
if v is None:
return []
if isinstance(v, list):
return v
if isinstance(v, str):
s = v.strip()
if not s:
return []
try:
parsed = json.loads(s)
if isinstance(parsed, list):
return parsed
except Exception:
pass
return [s]
return list(v)
def main():
pred_path, set_path, out_path = sys.argv[1:4]
csv.field_size_limit(sys.maxsize)
preds = {r["id"]: r.get("prediction") or "" for r in csv.DictReader(open(pred_path, newline="", encoding="utf-8"))}
rows = load_rows(set_path)
jobs = []
for r in rows:
jobs.append((
extract_code(preds.get(str(r["id"]), "")),
r.get("test") or "",
_list_field(r.get("test_list")),
_list_field(r.get("test_imports")),
))
workers = int(os.environ.get("LCB_EVAL_WORKERS", min(8, os.cpu_count() or 1)))
with ProcessPoolExecutor(max_workers=workers) as ex:
ok = list(ex.map(check, jobs))
total = len(rows)
correct = sum(ok)
out = {
"score": correct / total if total else 0.0,
"correct": correct,
"total": total,
"missing_predictions": sum(str(r["id"]) not in preds for r in rows),
}
json.dump(out, open(out_path, "w", encoding="utf-8"))
print(json.dumps(out))
if __name__ == "__main__":
main()