interplane.Get Omega
Read in your language

openaccel-lab

aien-dev/openaccel-lab

Brought by drakestapleton

branch main Branches Tags History

openaccel-lab / oal / run.py

243 lines · 9478 bytes Raw Blame History
1# SPDX-License-Identifier: Apache-2.0
2"""Backends: how each entrant is built and run. Every entrant is a program that reads one case
3container on stdin and writes the output tensors on stdout (docs/CONTAINER.md); this module only
4builds the program, runs it with a timeout and reads back stdout, the exit status and the
5"oal-time-ns" / "oal-version" lines on stderr.
6
7Statuses: PASS / FAIL come later from oal.check; here a run ends RAN, COMPILE_FAIL, RUNTIME_FAIL,
8TIMEOUT, COMPILED (built, deliberately not run: CUDA without a GPU), NOT_RUN (toolchain or platform
9missing) or NO_SOURCE (the workload has no entrant for this backend).
10
11INTERIM host glue (Python). Successor: oal-run in seeded Omega (fork/execprog/pipefds/waitpid
12host words exist in omc 369dbc96).
13"""
14import hashlib
15import os
16import platform
17import shutil
18import subprocess
19import sys
20
21from . import manifest
22
23ROOT = manifest.ROOT
24TOOLS = os.path.join(ROOT, ".oal")
25BACKENDS = ("omega", "opencl", "triton", "hip", "cuda")
26
27
28def _sha(path):
29 with open(path, "rb") as f:
30 return hashlib.sha256(f.read()).hexdigest()
31
32
33def _workdir(backend, name):
34 d = os.path.join(TOOLS, "build", backend, name)
35 os.makedirs(d, exist_ok=True)
36 return d
37
38
39def _scratch_args(m, params):
40 return [str(max(1, manifest.nbytes(s, params))) for s in m.get("scratch", [])]
41
42
43def _sh(cmd, **kw):
44 return subprocess.run(cmd, capture_output=True, **kw)
45
46
47def omc_path():
48 return os.environ.get("OAL_OMC", os.path.join(TOOLS, "tools", "omc"))
49
50
51def probe(backend):
52 """(available, detail): whether this machine can build/run the backend at all."""
53 if backend == "omega":
54 if platform.system() != "Linux" or platform.machine() not in ("aarch64", "arm64"):
55 return False, "Omega program mode emits Linux AArch64 only; this host is %s %s" % (
56 platform.system(), platform.machine())
57 p = omc_path()
58 return (os.access(p, os.X_OK), "omc %s sha256 %s" % (p, _sha(p)) if os.path.exists(p) else "omc missing at %s" % p)
59 if backend == "opencl":
60 try:
61 import pyopencl # noqa: F401
62 except ImportError:
63 return False, "pyopencl not installed"
64 return True, "pyopencl"
65 if backend == "triton":
66 try:
67 import triton # noqa: F401
68 import torch # noqa: F401
69 except ImportError:
70 return False, "triton or torch not installed"
71 return True, "triton"
72 if backend == "hip":
73 inc = os.environ.get("OAL_HIPCPU", os.path.join(TOOLS, "hip-cpu", "include"))
74 hip = os.environ.get("OAL_HIPIFY", os.path.join(TOOLS, "tools", "hipify-perl"))
75 if not os.path.isdir(inc) or not os.path.exists(hip):
76 return False, "HIP-CPU headers (%s) or hipify-perl (%s) missing" % (inc, hip)
77 return True, "HIP-CPU %s, hipify-perl sha256 %s" % (inc, _sha(hip))
78 if backend == "cuda":
79 nvcc = shutil.which(os.environ.get("OAL_NVCC", "nvcc"))
80 if not nvcc:
81 return False, "nvcc not found"
82 return True, nvcc
83 raise ValueError(backend)
84
85
86def _build_omega(m, wd):
87 src = os.path.join(m["_dir"], m["backends"]["omega"]["src"])
88 unit = os.path.join(wd, "unit.om")
89 with open(unit, "wb") as f:
90 f.write(open(os.path.join(ROOT, "lib", "omega", "oal.om"), "rb").read())
91 f.write(open(src, "rb").read())
92 exe = os.path.join(wd, "prog")
93 with open(unit, "rb") as fi, open(exe, "wb") as fo:
94 r = subprocess.run([omc_path()], stdin=fi, stdout=fo, stderr=subprocess.PIPE)
95 if r.returncode != 0:
96 os.unlink(exe)
97 return None, r.stderr.decode(errors="replace").strip() or "omc exit %d" % r.returncode
98 os.chmod(exe, 0o755)
99 return [exe], "omc exit 0, unit sha256 %s" % _sha(unit)
100
101
102def _cuda_unit(m, wd, hip):
103 src = os.path.join(m["_dir"], m["backends"]["cuda"]["src"])
104 unit = os.path.join(wd, "prog.cu")
105 with open(unit, "wb") as f:
106 f.write(open(src, "rb").read())
107 f.write(b"\n")
108 f.write(open(os.path.join(ROOT, "runners", "cuda", "host.cu"), "rb").read())
109 if not hip:
110 return unit, None
111 hipify = os.environ.get("OAL_HIPIFY", os.path.join(TOOLS, "tools", "hipify-perl"))
112 out = os.path.join(wd, "prog.hip.cpp")
113 # HIP-CPU has no triple-chevron launch: ask hipify for hipLaunchKernelGGL calls.
114 r = _sh(["perl", hipify, "-quiet-warnings", "-hip-kernel-execution-syntax", unit])
115 if r.returncode != 0:
116 return None, "hipify-perl: " + r.stderr.decode(errors="replace")
117 with open(out, "wb") as f:
118 f.write(r.stdout)
119 return out, None
120
121
122def _build_hip(m, wd):
123 unit, err = _cuda_unit(m, wd, hip=True)
124 if unit is None:
125 return None, err
126 inc = os.environ.get("OAL_HIPCPU", os.path.join(TOOLS, "hip-cpu", "include"))
127 exe = os.path.join(wd, "prog")
128 cxx = os.environ.get("CXX", "g++")
129 extra = os.environ.get("OAL_HIP_FLAGS", "").split()
130 # HIP-CPU e112c935 external/libco/aarch64.inl calls VALGRIND_STACK_REGISTER even when valgrind.h is
131 # absent; define it away (no-op on x86, where that file is not used).
132 shim = ["-DVALGRIND_STACK_REGISTER(a,b)=0"]
133 r = _sh([cxx, "-std=c++17", "-O2", "-I", inc] + shim + extra + ["-x", "c++", unit, "-o", exe, "-ltbb", "-lpthread"])
134 if r.returncode != 0:
135 return None, r.stderr.decode(errors="replace")[-4000:]
136 return [exe], "%s -std=c++17 -O2 HIP-CPU, hipified unit sha256 %s" % (cxx, _sha(unit))
137
138
139def _build_cuda(m, wd):
140 unit, _ = _cuda_unit(m, wd, hip=False)
141 nvcc = shutil.which(os.environ.get("OAL_NVCC", "nvcc"))
142 arch = os.environ.get("OAL_CUDA_ARCH", "sm_80")
143 exe = os.path.join(wd, "prog")
144 stamp = os.path.join(wd, "prog.stamp")
145 want = "%s %s" % (arch, _sha(unit))
146 # Reuse a build of the identical unit for the same arch, so a GPU run can be split into a build
147 # phase and a run phase (no compiler inside a GPU lock).
148 if os.path.exists(exe) and os.path.exists(stamp) and open(stamp).read().split("\n")[0] == want:
149 return [exe], open(stamp).read().split("\n", 1)[1].strip() + " (reused build)"
150 r = _sh([nvcc, "-O2", "-arch=" + arch, "-o", exe, unit])
151 if r.returncode != 0:
152 return None, r.stderr.decode(errors="replace")[-4000:]
153 v = _sh([nvcc, "--version"]).stdout.decode().strip().splitlines()[-1]
154 log = "nvcc -O2 -arch=%s (%s)" % (arch, v)
155 with open(stamp, "w") as f:
156 f.write(want + "\n" + log + "\n")
157 return [exe], log
158
159
160_BUILT = {}
161
162
163def build(backend, m):
164 """(argv or None, log). argv is the entrant program without scratch arguments; one build per
165 (backend, workload) per process."""
166 key = (backend, m["name"])
167 if key not in _BUILT:
168 _BUILT[key] = _build(backend, m)
169 return _BUILT[key]
170
171
172def _build(backend, m):
173 wd = _workdir(backend, m["name"])
174 if backend == "omega":
175 return _build_omega(m, wd)
176 if backend == "opencl":
177 return [sys.executable, "-m", "oal.entrants.opencl", m["name"]], "pyopencl host"
178 if backend == "triton":
179 return [sys.executable, "-m", "oal.entrants.triton", m["name"]], "triton host"
180 if backend == "hip":
181 return _build_hip(m, wd)
182 if backend == "cuda":
183 return _build_cuda(m, wd)
184 raise ValueError(backend)
185
186
187def source_for(backend, m):
188 b = m["backends"]
189 if backend == "hip":
190 return b.get("hip") or ("cuda" in b and {"from": "cuda"})
191 return b.get(backend)
192
193
194def execute(backend, m, params, blob, timeout):
195 """Build and run one entrant on one case. Returns a dict; outputs (bytes) only when status RAN."""
196 res = {"status": None, "times_ns": [], "versions": [], "log": ""}
197 if not source_for(backend, m):
198 res["status"] = "NO_SOURCE"
199 return res
200 ok, detail = probe(backend)
201 res["toolchain"] = detail
202 if not ok:
203 res["status"] = "NOT_RUN"
204 res["log"] = detail
205 return res
206 argv, log = build(backend, m)
207 res["build"] = log
208 if argv is None:
209 res["status"] = "COMPILE_FAIL"
210 res["log"] = log
211 return res
212 if backend == "cuda" and os.environ.get("OAL_CUDA_RUN") != "1":
213 res["status"] = "COMPILED"
214 res["log"] = "built; not run (no GPU on this runner; OAL_CUDA_RUN unset)"
215 return res
216 env = dict(os.environ)
217 env["PYTHONPATH"] = ROOT + os.pathsep + env.get("PYTHONPATH", "")
218 try:
219 r = subprocess.run(argv + _scratch_args(m, params), input=blob, capture_output=True,
220 timeout=timeout, env=env, cwd=ROOT)
221 except subprocess.TimeoutExpired:
222 res["status"] = "TIMEOUT"
223 res["log"] = "no exit within %ds" % timeout
224 return res
225 err = r.stderr.decode(errors="replace")
226 other = []
227 for line in err.splitlines():
228 if line.startswith("oal-time-ns "):
229 res["times_ns"].append(int(line.split()[1]))
230 elif line.startswith("oal-version "):
231 res["versions"].append(line[len("oal-version "):])
232 else:
233 other.append(line)
234 res["log"] = "\n".join(other)[-4000:]
235 res["exit"] = r.returncode
236 if r.returncode != 0:
237 res["status"] = "COMPILE_FAIL" if (backend == "opencl" and r.returncode == 2) else "RUNTIME_FAIL"
238 if backend == "omega" and r.returncode > 100:
239 res["log"] = ("trap %d. " % (r.returncode - 100)) + res["log"]
240 return res
241 res["status"] = "RAN"
242 res["outputs"] = r.stdout
243 return res