File size: 5,330 Bytes
bbc5c85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
#!/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()