File size: 13,049 Bytes
902d2bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: CC-BY-NC-4.0
"""The interface to the public SOL-ExecBench harness: run its CLI once, read only this call's trace."""
from __future__ import annotations

import ast
import contextlib
import fcntl
import hashlib
import io
import json
import os
import re
import secrets
import shutil
import signal
import subprocess
import textwrap
import tokenize

# NVIDIA's command-line tool, from github.com/nvidia/sol-execbench. It is not part of this package.
CLI = "sol-execbench"
LATENCY_FLOOR_MS = 1e-4            # a time below 0.1 us is not a real measurement
FAIL_CLASS = {"COMPILE_ERROR": "compile_fail", "TIMEOUT": "timeout",
              "RUNTIME_ERROR": "runtime_error", "INCORRECT_NUMERICAL": "wrong_answer",
              "INCORRECT_SHAPE": "wrong_answer", "INCORRECT_DTYPE": "wrong_answer"}
CLASS_ORDER = ("compile_fail", "timeout", "runtime_error", "wrong_answer", "incomplete", "other")
QUICK_CONFIG = {"warmup_runs": 0, "iterations": 1}      # correctness-only runs (checks, compile)
C_LIKE = (".cu", ".cuh", ".c", ".cc", ".cpp", ".cxx", ".h", ".hh", ".hpp", ".inl")


# -- one harness run ----------------------------------------------------------------------------

@contextlib.contextmanager
def gpu_lock(gpu_id, lock_dir):
    """One timed run per GPU: an exclusive file lock per GPU id, across processes and threads."""
    if gpu_id is None or not lock_dir:
        yield
        return
    os.makedirs(lock_dir, exist_ok=True)
    with open(os.path.join(lock_dir, "gpu%d.lock" % int(gpu_id)), "a") as f:
        fcntl.flock(f, fcntl.LOCK_EX)
        try:
            yield
        finally:
            fcntl.flock(f, fcntl.LOCK_UN)


def run_cli(cmd, timeout_s, env=None):
    """(return code, or None on a timeout; the combined output). The run gets its own process group."""
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env,
                         encoding="utf-8", errors="replace", start_new_session=True)
    try:
        out, _ = p.communicate(timeout=timeout_s)
        return p.returncode, out or ""
    except subprocess.TimeoutExpired:
        with contextlib.suppress(ProcessLookupError):
            os.killpg(p.pid, signal.SIGKILL)       # the whole group: the CLI and its eval driver
        out, _ = p.communicate()
        return None, out or ""


def evaluate(problem_dir, solution_path, out_dir, gpu_id=None, lock_dir=None, workload_path=None,
             config_path=None, compile_timeout_s=300, eval_timeout_s=900, env=None, prefix=()):
    """Run the harness on one solution. correct = a PASSED row for every workload, and no other row."""
    os.makedirs(out_dir, exist_ok=True)
    if shutil.which(CLI) is None:
        return {"compiled": False, "correct": False, "fail_class": "harness_not_found",
                "rows": [], "flags": [], "rc": None, "output": ""}
    trace = os.path.join(out_dir, "trace-%s.jsonl" % secrets.token_hex(6))   # this call's own
    if workload_path is None:
        target, workload_path = [problem_dir], os.path.join(problem_dir, "workload.jsonl")
    else:
        target = ["--definition", os.path.join(problem_dir, "definition.json"),
                  "--workload", workload_path]
    cmd = list(prefix) + [CLI] + target + [
        "--solution", solution_path, "--compile-timeout", str(int(compile_timeout_s)),
        "--timeout", str(int(eval_timeout_s)), "-o", trace]
    if config_path:
        cmd += ["--config", config_path]
    run_env = dict(os.environ if env is None else env)
    if gpu_id is not None:
        run_env["CUDA_VISIBLE_DEVICES"] = str(gpu_id)
    with gpu_lock(gpu_id, lock_dir):
        rc, out = run_cli(cmd, compile_timeout_s + eval_timeout_s + 120, run_env)
    workloads = [w for w in read_jsonl(workload_path) if isinstance(w, dict)]
    res = verdict(parse_trace(trace), workloads, rc, out)
    res.update(rc=rc, output=out)
    return res


def parse_trace(path):
    """One row per trace line: workload uuid and axes, status, times, errors (a torn line fails)."""
    rows = []
    for rec in read_jsonl(path) if os.path.exists(path) else []:
        ev = rec.get("evaluation") if isinstance(rec, dict) else None
        if not isinstance(ev, dict):
            rows.append({"uuid": None, "axes": None, "status": "UNPARSEABLE"})
            continue
        wl = rec.get("workload") if isinstance(rec.get("workload"), dict) else {}
        perf, corr = ev.get("performance") or {}, ev.get("correctness") or {}
        rows.append({"uuid": wl.get("uuid"), "axes": wl.get("axes"), "status": ev.get("status"),
                     "latency_ms": perf.get("latency_ms"),
                     "reference_latency_ms": perf.get("reference_latency_ms"),
                     "max_abs_error": corr.get("max_absolute_error"),
                     "max_rel_error": corr.get("max_relative_error"),
                     "nonfinite": bool(corr.get("has_nan") or corr.get("has_inf")),
                     "log": (ev.get("log") or "")[-1500:]})
    return rows


def coverage(rows, workloads):
    """(missing workloads, extra rows): rows are matched to workloads by uuid, as a multiset."""
    want = {}
    for w in workloads:
        want[w.get("uuid")] = want.get(w.get("uuid"), 0) + 1
    extra = 0
    for r in rows:
        if want.get(r.get("uuid")):
            want[r.get("uuid")] -= 1
        else:
            extra += 1
    return sum(want.values()), extra


def verdict(rows, workloads, rc, output):
    """Correctness, the first failure class, the mean time of the passed rows, and flags."""
    missing, extra = coverage(rows, workloads)
    passed = [r for r in rows if r.get("status") == "PASSED"]
    correct = bool(rows) and len(passed) == len(rows) and not missing and not extra
    fail = None
    if not correct:
        classes = {FAIL_CLASS.get(r.get("status"), "other") for r in rows
                   if r.get("status") != "PASSED"}
        if rows and (missing or extra):
            classes.add("incomplete")
        if not rows:
            classes.add("timeout" if rc is None else
                        "compile_fail" if "Compilation failed" in output else "runtime_error")
        fail = min(classes, key=CLASS_ORDER.index)
    times = [r["latency_ms"] for r in passed if r.get("latency_ms") is not None]
    return {"compiled": bool(rows), "correct": correct, "fail_class": fail,
            "n_workloads": len(workloads), "n_passed": len(passed),
            "t_k_ms_mean": sum(times) / len(times) if times else None,
            "flags": ["impossibly_fast"] if any(t < LATENCY_FLOOR_MS for t in times) else [],
            "rows": rows}


# -- small helpers for the checks -----------------------------------------------------------------

def read_jsonl(path):
    """The JSON value of each non-empty line (None for a line that does not parse)."""
    out = []
    with open(path, encoding="utf-8", errors="replace") as f:
        for line in f:
            if line.strip():
                try:
                    out.append(json.loads(line))
                except ValueError:
                    out.append(None)
    return out


def write_jsonl(path, rows):
    with open(path, "w", encoding="utf-8") as f:
        f.writelines(json.dumps(r) + "\n" for r in rows)
    return path


def quick_config(out_dir):
    """A benchmark config for correctness-only runs (no warmup, one timed call)."""
    path = os.path.join(out_dir, "quick_config.json")
    with open(path, "w", encoding="utf-8") as f:
        json.dump(QUICK_CONFIG, f)
    return path


def smallest_workload(problem_dir):
    """The shipped workload with the smallest product of axis values (for short checks)."""
    rows = [w for w in read_jsonl(os.path.join(problem_dir, "workload.jsonl"))
            if isinstance(w, dict)]

    def size(w):
        n = 1
        for v in (w.get("axes") or {}).values():
            n *= max(1, int(v)) if isinstance(v, (int, float)) else 1
        return n
    return min(rows, key=size) if rows else None


def site_env(env, snippets, site_dir, paths=()):
    """A copy of env whose Python processes run each snippet at start (a sitecustomize.py)."""
    # Note: this sitecustomize shadows any other one on the path of the eval process.
    os.makedirs(site_dir, exist_ok=True)
    body = "".join("try:\n%s\nexcept Exception:\n    pass\n" % textwrap.indent(s, "    ")
                   for s in snippets)
    with open(os.path.join(site_dir, "sitecustomize.py"), "w", encoding="utf-8") as f:
        f.write(body)
    out = dict(os.environ if env is None else env)
    out["PYTHONPATH"] = os.pathsep.join([site_dir] + list(paths) +
                                        ([out["PYTHONPATH"]] if out.get("PYTHONPATH") else []))
    return out


# -- source text: comments, dead code, and the "unchanged code" key ------------------------------

_C_TOKEN = re.compile(r'//[^\n]*|/\*.*?(?:\*/|$)|(?<!\w)(?:u8|[uUL])?R"([^()\\\s]{0,16})\(.*?\)\1"'
                      r'|"(?:\\.|[^"\\\n])*"|\'(?:\\.|[^\'\\\n])*\'', re.S)
_IF0 = re.compile(r"\s*#\s*if\s+(?:0|false)\b")
_IF, _ELSE, _ENDIF = (re.compile(r"\s*#\s*if"), re.compile(r"\s*#\s*(?:else|elif)\b"),
                      re.compile(r"\s*#\s*endif\b"))


def _blank(s):
    return re.sub(r"[^\n]", " ", s)


def _py_docstrings(text):
    """(line, col) of every docstring in a Python source."""
    kinds = (ast.Module, ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)
    return {(n.body[0].value.lineno, n.body[0].value.col_offset) for n in ast.walk(ast.parse(text))
            if isinstance(n, kinds) and n.body and isinstance(n.body[0], ast.Expr)
            and isinstance(n.body[0].value, ast.Constant) and isinstance(n.body[0].value.value, str)}


def strip_comments(path, text):
    """The source with comments (and Python docstrings) blanked; line numbers stay the same."""
    if path.lower().endswith(C_LIKE):
        return _C_TOKEN.sub(lambda m: _blank(m.group()) if m.group()[:2] in ("//", "/*")
                            else m.group(), text)
    if not path.endswith(".py"):
        return text
    try:
        docs = _py_docstrings(text)
        spans = [(t.start, t.end) for t in tokenize.generate_tokens(io.StringIO(text).readline)
                 if t.type == tokenize.COMMENT or (t.type == tokenize.STRING and t.start in docs)]
    except (SyntaxError, tokenize.TokenError, ValueError):
        return text
    starts = [0]                           # offset of each line, split as tokenize splits them
    for ln in text.split("\n"):
        starts.append(starts[-1] + len(ln) + 1)
    out = list(text)
    for (r0, c0), (r1, c1) in spans:
        a, b = starts[r0 - 1] + c0, starts[r1 - 1] + c1
        out[a:b] = _blank(text[a:b])
    return "".join(out)


def code_only(path, text):
    """strip_comments, and in C-like sources every `#if 0` block blanked too."""
    text = strip_comments(path, text)
    if not path.lower().endswith(C_LIKE):
        return text
    out, depth = [], 0                     # depth > 0: inside a dead block (nested #if counted)
    for line in text.split("\n"):
        if depth == 0 and _IF0.match(line):
            depth = 1
        elif depth:
            if _IF.match(line):
                depth += 1
            elif _ENDIF.match(line):
                depth -= 1
            elif depth == 1 and _ELSE.match(line):
                depth = 0                   # the #else branch of `#if 0` is live
                out.append(line)
                continue
        else:
            out.append(line)
            continue
        out.append("")
    return "\n".join(out)


def normalized(path, text):
    """The code without comments and spacing: C-like per line, Python as its token stream."""
    if path.endswith(".py"):
        try:
            toks = tokenize.generate_tokens(io.StringIO(text).readline)
            return json.dumps([[t.type, t.string] for t in toks
                               if t.type not in (tokenize.COMMENT, tokenize.NL)])
        except (SyntaxError, tokenize.TokenError, ValueError):
            return text
    if not path.lower().endswith(C_LIKE):
        return text
    parts, pos = [], 0
    for m in _C_TOKEN.finditer(text):
        parts.append(re.sub(r"[ \t\f\v]+", " ", text[pos:m.start()]))
        parts.append(" " if m.group()[:2] in ("//", "/*") else m.group())   # literals kept exact
        pos = m.end()
    parts.append(re.sub(r"[ \t\f\v]+", " ", text[pos:]))
    return "\n".join(ln.strip() for ln in "".join(parts).split("\n") if ln.strip())


def solution_key(sol):
    """Same key = the same code once comments and spacing are gone: it is not timed again."""
    srcs = [[str(s.get("path", "")), normalized(str(s.get("path", "")), str(s.get("content", "")))]
            for s in sol.get("sources") or [] if isinstance(s, dict)]
    blob = json.dumps({"spec": sol.get("spec"), "sources": srcs}, sort_keys=True)
    return hashlib.sha256(blob.encode("utf-8", "surrogatepass")).hexdigest()