Repository navigation
Expand file tree
/
Copy pathtest.py
More file actions
263 lines (227 loc) · 8.81 KB
/
Copy pathtest.py
File metadata and controls
263 lines (227 loc) · 8.81 KB
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
# Data Parallel Control (dpctl)
#
# Copyright 2026 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Tests dpctl's installed package.
Runs with one built package installed in a clean environment, as ci/hooks.py
sets up, from an empty working directory, so the tests import the installed
dpctl rather than the source tree. The test requirements come from
ci/config.yml. Writes a JUnit report to $GH_CI_RESULTS.
The environment is scrubbed, so this sets what dpctl needs itself. It prints the
SYCL devices and fails without any, so a run that skipped every device test
cannot pass. With GH_CI_DEVICE=gpu a GPU device is required too. Without it the
OpenCL CPU runtime from the test environment is the device, as on GitHub's
runners.
"""
import json
import os
import pathlib
import subprocess
import sys
import sysconfig
import tempfile
PACKAGE = "dpctl"
# Where intel-opencl-rt installs its CPU runtime: the conda package in
# intel-ocl-cpu/ of that directory, the PyPI wheel in it
CPU_ICD = {
"win32": ("Library/bin", "intelocl64.dll"),
"linux": ("lib", "libintelocl.so"),
}
DEVICES = """
import json
import dpctl
print(json.dumps([
[d.backend.name, d.device_type.name, d.name] for d in dpctl.get_devices()
]))
"""
PROBE_SETUP = """
import setuptools
setuptools.setup(
name="probe",
ext_modules=[
setuptools.Extension("probe_c", ["probe_c.c"], language="c"),
setuptools.Extension("probe_cpp", ["probe_cpp.cpp"], language="c++"),
],
)
"""
PROBE_SOURCE = """
#include <Python.h>
static struct PyModuleDef module = {PyModuleDef_HEAD_INIT, "NAME", 0, -1, 0};
PyMODINIT_FUNC PyInit_NAME(void) { return PyModule_Create(&module); }
"""
# These two tests build extensions with the Python environment's compiler.
NEED_COMPILER = ["test_c_headers", "test_cython_api"]
def running_python() -> str:
"""This interpreter's version as artifact names spell it, such as 3.14t."""
version = f"{sys.version_info.major}.{sys.version_info.minor}"
threaded = sysconfig.get_config_var("Py_GIL_DISABLED")
return version + ("t" if threaded else "")
def has_compilers(env: dict) -> bool:
"""Whether setuptools can build a C and a C++ extension."""
with tempfile.TemporaryDirectory() as scratch:
directory = pathlib.Path(scratch)
(directory / "setup.py").write_text(PROBE_SETUP, encoding="utf-8")
for language, suffix in (("c", "c"), ("c++", "cpp")):
source = PROBE_SOURCE.replace("NAME", f"probe_{suffix}")
(directory / f"probe_{suffix}.{suffix}").write_text(
source, encoding="utf-8"
)
built = subprocess.run(
[sys.executable, "setup.py", "build_ext", "--inplace"],
cwd=directory,
env=env,
capture_output=True,
text=True,
check=False,
)
if built.returncode:
print(
f"no usable compiler:\n{built.stdout[-1500:]}{built.stderr[-1500:]}"
)
return not built.returncode
def compilers_installed() -> bool:
"""Whether the environment has conda-forge's compiler packages."""
meta = pathlib.Path(sys.prefix, "conda-meta")
return any(meta.glob("c-compiler-*.json")) or any(
meta.glob("cxx-compiler-*.json")
)
def skipped_tests(compilers: bool) -> list:
"""The tests this environment cannot run, said out loud."""
skipped = []
if os.environ.get("GH_CI_KIND") == "wheel":
print("deselecting test_syclinterface: a wheel keeps no symlinks")
skipped.append("test_syclinterface")
if not compilers:
print(f"deselecting {', '.join(NEED_COMPILER)}: they need a compiler")
skipped += NEED_COMPILER
return skipped
def cpu_runtime_icd() -> str | None:
"""The OpenCL CPU runtime of the test environment, if it has one."""
directory, name = CPU_ICD.get(sys.platform, CPU_ICD["linux"])
base = pathlib.Path(sys.prefix, directory)
for path in (base / "intel-ocl-cpu" / name, base / name):
if path.is_file():
return str(path)
return None
def merge_icd_vendors(env: dict, merged: pathlib.Path) -> None:
"""Lets the environment's OpenCL loader see the system's GPU drivers too."""
system = pathlib.Path("/etc/OpenCL/vendors")
own = pathlib.Path(sys.prefix, "etc", "OpenCL", "vendors")
if not (system.is_dir() and own.is_dir()):
return
for icd in [*own.glob("*.icd"), *system.glob("*.icd")]:
if not (merged / icd.name).exists():
(merged / icd.name).symlink_to(icd)
env["OCL_ICD_VENDORS"] = str(merged)
def register_icd(icd: str) -> None:
"""Registers the ICD in the registry, which Windows' loader reads."""
import winreg
try:
with winreg.CreateKeyEx(
winreg.HKEY_LOCAL_MACHINE,
r"SOFTWARE\Khronos\OpenCL\Vendors",
0,
winreg.KEY_SET_VALUE,
) as vendors:
winreg.SetValueEx(vendors, icd, 0, winreg.REG_DWORD, 0)
except OSError as error:
print(f"could not register {icd}: {error}")
def sycl_env(gpu: bool, merged: pathlib.Path) -> dict:
"""The environment dpctl runs in."""
env = dict(os.environ, SYCL_CACHE_PERSISTENT="1")
if sys.platform == "win32":
# setuptools finds Visual C++ from these, and the scrubbed environment
# lacks them.
drive = env.get("SYSTEMDRIVE", "C:")
env.setdefault("PROGRAMFILES", drive + "\\Program Files")
env.setdefault("PROGRAMFILES(X86)", drive + "\\Program Files (x86)")
if gpu:
if sys.platform.startswith("linux"):
merge_icd_vendors(env, merged)
return env
# Linux and newer Windows loaders take the ICD from here.
icd = cpu_runtime_icd()
if icd:
env["OCL_ICD_FILENAMES"] = icd
if sys.platform == "win32":
register_icd(icd)
return env
def devices(env: dict) -> list:
"""The [backend, type, name] of every SYCL device, in a fresh process."""
listed = subprocess.run(
[sys.executable, "-c", DEVICES],
env=env,
capture_output=True,
text=True,
check=False,
)
if listed.returncode:
print(listed.stderr)
return []
return json.loads(listed.stdout)
def devices_ok(found: list, gpu: bool) -> bool:
"""Prints the devices, and whether the ones the tests need are there."""
for backend, kind, name in found:
print(f"SYCL device: {backend}:{kind} {name}")
if not found:
print("no SYCL device, so the tests would skip everything")
return False
if gpu and not any(kind == "gpu" for _, kind, _ in found):
print("GH_CI_DEVICE=gpu, but there is no GPU device")
return False
return True
def main() -> int:
"""Runs the installed package's test suite."""
sys.stdout.reconfigure(line_buffering=True)
expected = os.environ["GH_CI_PYTHON"]
if running_python() != expected:
print(f"running Python {running_python()}, expected {expected}")
return 1
gpu = os.environ.get("GH_CI_DEVICE") == "gpu"
with tempfile.TemporaryDirectory() as merged:
env = sycl_env(gpu, pathlib.Path(merged))
listed = subprocess.run(
[sys.executable, "-m", "dpctl", "-f"], env=env, check=False
)
if listed.returncode:
print(f"python -m dpctl -f failed with exit {listed.returncode}")
return listed.returncode
if not devices_ok(devices(env), gpu):
return 1
compilers = has_compilers(env)
if not compilers and compilers_installed():
print("the environment's compilers cannot build an extension")
return 1
# The suite name says which platform and Python ran.
cell = f"{os.environ.get('GH_CI_PLATFORM', 'linux')}.py{expected}"
report = pathlib.Path(os.environ["GH_CI_RESULTS"]) / f"{PACKAGE}.xml"
pytest = [
sys.executable,
"-m",
"pytest",
"-v",
"-p",
"no:cacheprovider",
f"--junitxml={report}",
"-o",
f"junit_suite_name={PACKAGE} {cell}",
"--pyargs",
PACKAGE,
]
if skipped := skipped_tests(compilers):
pytest += ["-k", "not " + " and not ".join(skipped)]
return subprocess.run(pytest, env=env, check=False).returncode
if __name__ == "__main__":
sys.exit(main())