QianQu's picture
Upload folder using huggingface_hub
902d2bb verified
Raw History Blame Contribute Delete
13 kB
# 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()