diff --git a/scripts/gpu_test_setup.py b/scripts/gpu_test_setup.py new file mode 100644 index 0000000000..b71d202afd --- /dev/null +++ b/scripts/gpu_test_setup.py @@ -0,0 +1,212 @@ +"""What this machine can run of the GPU tests right now, and the command for it. + + python -I scripts/gpu_test_setup.py [--build DIR] [--llvm-mc CMD] [--json] + +docs/testing.md lists everything the GPU tests can use: llvm-mc with the AMDGPU target, SPIRV-Tools, the Vulkan +test programs of runtime/, a GPU. Not all of it is needed for a first result, and which part is missing shows +only when a run stops. This looks once and says what is there and how far it gets: + +- `semantic`: the translator suite. Needs Python alone. +- `subset`: `run_gpu_tests.py --disasm-dir tests/semantic/fixtures/disasm`, the fixtures that are kept as + listings, assembled by tools/spirv_asm.py when spirv-as is missing. Needs the three test programs and a GPU, + but neither llvm-mc nor SPIRV-Tools. +- `full`: every fixture of runtime/test/shaders. Needs llvm-mc with the AMDGPU target as well, and the test + programs the texture, sampler and bindless fixtures start. + +For each level it prints the command, or what is missing for it. It also names the GPUs `vulkaninfo` reports with +their subgroup range: a device whose largest subgroup is below 64 runs the wave64 fixtures only with +`LEONIDA_W64_EMULATE=1`, so a record for it needs both runs. + +It starts `llvm-mc --version`, `spirv-as --version`, `spirv-val --version` and `vulkaninfo`, reads their output and +looks for files; it builds nothing, runs no test and writes nothing. Exit 0 when it ran, 2 on a usage error. +Standard library only; no game files. +""" +import argparse +import json +import os +import re +import shutil +import subprocess +import sys + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(ROOT, "tools")) + +import mc_command # noqa: E402 + +PROGRAMS = ("vk_compute_test", "vk_store_test", "vk_harness") # REQUIRED_TEST_PROGRAMS of run_gpu_tests.py +# What the full run starts as well: without one of them its fixtures fail with "could not start". +MORE_PROGRAMS = ("vk_texture_test", "vk_bindless_test", "vk_sampler_test", "d3d12_texture_uav_test") +CONFIGS = ("", "RelWithDebInfo", "Release") +BUILDS = ("runtime/build", "runtime/build/linux", "runtime/build/windows") +FIXTURES = "tests/semantic/fixtures/disasm" + + +def output_of(cmd, timeout=60): + """What a command prints, or None when it cannot be started or fails.""" + try: + r = subprocess.run(cmd, capture_output=True, timeout=timeout) + except (OSError, subprocess.TimeoutExpired): + return None + text = (r.stdout + r.stderr).decode("utf-8", "replace") + return text if r.returncode == 0 else None + + +def llvm_mc(raw): + """{"command", "version", "amdgpu"} for the llvm-mc that LLVM_MC, --llvm-mc or PATH names; None without one.""" + try: + cmd = mc_command.mc_command(raw) + except (ValueError, OSError): + return None + text = output_of([*cmd, "--version"]) + if text is None: + return None + version = re.search(r"LLVM version (\S+)", text) + return {"command": " ".join(cmd), "version": version.group(1) if version else None, + "amdgpu": "amdgcn" in text.lower()} + + +def tool(name): + """The path of a SPIRV-Tools program that starts, or None.""" + path = shutil.which(name) + return path if path and output_of([path, "--version"]) is not None else None + + +def gpus(text): + """[{"name", "driver", "subgroup": [min, max] or None}] from `vulkaninfo` text, one per device.""" + found = [] + for block in re.split(r"(?m)^GPU\d+:\s*$", text or "")[1:]: + name = re.search(r"(?m)^\s*deviceName\s*=\s*(.+?)\s*$", block) + if not name: + continue + low = re.search(r"(?m)^\s*minSubgroupSize\s*=\s*(\d+)", block) + high = re.search(r"(?m)^\s*maxSubgroupSize\s*=\s*(\d+)", block) + driver = re.search(r"(?m)^\s*driverInfo\s*=\s*(.+?)\s*$", block) + entry = next((g for g in found if g["name"] == name.group(1)), None) + if entry is None: + entry = {"name": name.group(1), "driver": None, "subgroup": None} + found.append(entry) + if driver: + entry["driver"] = driver.group(1) + if low and high: + entry["subgroup"] = [int(low.group(1)), int(high.group(1))] + return found + + +def test_programs(root, builds): + """The first folder that holds all three test programs, as run_gpu_tests.py looks for them.""" + ext = ".exe" if os.name == "nt" else "" + for build in builds: + for config in CONFIGS: + folder = os.path.join(root, build, config) if not os.path.isabs(build) else os.path.join(build, config) + if all(os.path.isfile(os.path.join(folder, name + ext)) for name in PROGRAMS): + return os.path.normpath(os.path.join(build, config)) + return None + + +def survey(root=ROOT, build=None, raw_llvm_mc=None): + try: + listings = sum(1 for name in os.listdir(os.path.join(root, FIXTURES)) if name.endswith(".s")) + except OSError: + listings = 0 + state = { + "llvm_mc": llvm_mc(raw_llvm_mc), + "spirv_as": tool("spirv-as"), "spirv_val": tool("spirv-val"), + "gpus": gpus(output_of(["vulkaninfo"])), + "build": test_programs(root, [build] if build else BUILDS), + "llvm_mc_option": raw_llvm_mc, + "more_missing": [], + "listings": listings, + } + if state["build"]: + folder = state["build"] if os.path.isabs(state["build"]) else os.path.join(root, state["build"]) + ext = ".exe" if os.name == "nt" else "" + state["more_missing"] = [n for n in MORE_PROGRAMS if not os.path.isfile(os.path.join(folder, n + ext))] + state["levels"] = levels(state, build) + return state + + +def quoted(text): + """`text` as one argument of a shell command: in double quotes when it has a space, which PowerShell, cmd + and POSIX shells all take.""" + return f'"{text}"' if " " in text else text + + +def levels(state, build=None): + """[{"level", "ready", "command", "missing": [..]}] for semantic, subset and full.""" + where = (state["build"] or build or BUILDS[0]).replace(os.sep, "/") + no_programs = (f"the test programs {', '.join(PROGRAMS)} in {where}: cmake -S runtime -B runtime/build, then " + "cmake --build runtime/build (CMake builds them only when it finds the Vulkan headers)") + no_gpu = "a Vulkan device: vulkaninfo reports none" + common = ([] if state["build"] else [no_programs]) + ([] if state["gpus"] else [no_gpu]) + mc = state["llvm_mc"] + if mc is None: + no_mc = ["llvm-mc: " + mc_command.install_hint()] + elif not mc["amdgpu"]: + no_mc = [f"an llvm-mc with the AMDGPU target: {mc['command']} has none (the official Windows build lacks it)"] + else: + no_mc = [] + more = ([f"the test programs {', '.join(state['more_missing'])} in {where}: cmake --build without --target " + "builds them (the d3d12 one on Windows only)"] if state.get("more_missing") else []) + run = f"python -I scripts/run_gpu_tests.py --build {quoted(where)}" + return [ + {"level": "semantic", "ready": True, "missing": [], + "command": "python -I scripts/run_semantic_tests.py tests/semantic"}, + {"level": "subset", "ready": not common and state["listings"] > 0, + "missing": common + ([] if state["listings"] else [f"the listings in {FIXTURES}"]), + "command": f"{run} --disasm-dir {FIXTURES}"}, + {"level": "full", "ready": not common and not no_mc and not more, "missing": common + more + no_mc, + # An llvm-mc named on this command line is not in LLVM_MC: the runner has to be told as well. + "command": run + (f" --llvm-mc {quoted(state['llvm_mc_option'])}" if state.get("llvm_mc_option") else "")}, + ] + + +def print_report(state): + mc = state["llvm_mc"] + print("llvm-mc: " + ("not found" if mc is None else + f"{mc['command']} ({mc['version'] or 'version unknown'}, " + + ("AMDGPU target" if mc["amdgpu"] else "no AMDGPU target") + ")")) + for key, name in (("spirv_as", "spirv-as"), ("spirv_val", "spirv-val")): + fallback = "tools/spirv_asm.py assembles instead" if key == "spirv_as" else "validation is skipped" + print(f"{name + ':':<12}" + (state[key] or f"not found ({fallback})")) + print("programs: " + (state["build"].replace(os.sep, "/") if state["build"] else "not built")) + print(f"listings: {state['listings']} in {FIXTURES}") + if not state["gpus"]: + print("GPU: none reported by vulkaninfo") + for gpu in state["gpus"]: + sub = gpu["subgroup"] + note = ("" if sub is None else f", subgroup {sub[0]}..{sub[1]}" + + ("" if sub[1] >= 64 else ": wave64 fixtures need LEONIDA_W64_EMULATE=1")) + print(f"GPU: {gpu['name']}" + (f" ({gpu['driver']})" if gpu["driver"] else "") + note) + print() + for level in state["levels"]: + print(f"{level['level']}: " + ("ready" if level["ready"] else "not yet")) + if level["ready"]: + print(f" {level['command']}") + for item in level["missing"]: + print(f" needs {item}") + if any(g["subgroup"] and g["subgroup"][1] < 64 for g in state["gpus"]) and state["levels"][1]["ready"]: + print("\nOn a device without 64-wide subgroups, run the GPU command a second time with LEONIDA_W64_EMULATE=1 " + "set;\nselect a device with LEONIDA_VK_DEVICE=.") + + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__.strip().splitlines()[0]) + ap.add_argument("--build", help="CMake build folder of runtime/ (default: runtime/build and its usual variants)") + ap.add_argument("--llvm-mc", help="llvm-mc path or whole command (default: LLVM_MC, then PATH)") + ap.add_argument("--json", action="store_true", help="one JSON object instead of text") + args = ap.parse_args(argv) + state = survey(ROOT, build=args.build, raw_llvm_mc=args.llvm_mc) + if args.json: + print(json.dumps(state, indent=2)) + else: + print_report(state) + return 0 + + +if __name__ == "__main__": + try: + sys.stdout.reconfigure(errors="replace") + except (AttributeError, ValueError, OSError): + pass + sys.exit(main()) diff --git a/tests/test_gpu_test_setup.py b/tests/test_gpu_test_setup.py new file mode 100644 index 0000000000..5c437aa83f --- /dev/null +++ b/tests/test_gpu_test_setup.py @@ -0,0 +1,245 @@ +"""scripts/gpu_test_setup.py with stand-in tools and folders (no GPU, no llvm-mc, no game data). + + python -I tests/test_gpu_test_setup.py + +The programs it would start are replaced by their recorded output; the build folder and the listings are made in +a temporary checkout. +""" +import contextlib +import io +import json +import os +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(ROOT, "scripts")) + +import gpu_test_setup as setup # noqa: E402 + +VULKANINFO = """\ +Devices: +======== +GPU0: +\tapiVersion = 1.4.351 +\tdeviceName = Vendor One 9000 +\tdriverInfo = 617.42 +GPU1: +\tdeviceName = Vendor Two Graphics +\tdriverInfo = 25.10.36 (proprietary) + +GPU0: +\tdeviceName = Vendor One 9000 +\tminSubgroupSize = 32 +\tmaxSubgroupSize = 32 +GPU1: +\tdeviceName = Vendor Two Graphics +\tminSubgroupSize = 32 +\tmaxSubgroupSize = 64 +""" +AMDGPU = "LLVM version 23.1.6\n Registered Targets:\n amdgcn - AMD GCN GPUs\n x86 - 32-bit X86\n" +PLAIN = "LLVM version 21.1.0\n Registered Targets:\n x86 - 32-bit X86\n" + + +class SetupCase(unittest.TestCase): + def setUp(self): + td = tempfile.TemporaryDirectory(prefix="leonida gpu_test_setup ") + self.addCleanup(td.cleanup) + self.root = td.name + self.outputs = {"vulkaninfo": VULKANINFO} + self.on_path = set() + for patcher in (mock.patch.object(setup, "output_of", self.output_of), + mock.patch.object(setup.shutil, "which", lambda name: name if name in self.on_path else None), + mock.patch.dict(os.environ, {"LLVM_MC": ""})): + patcher.start() + self.addCleanup(patcher.stop) + + def output_of(self, cmd, timeout=60): + return self.outputs.get(os.path.basename(cmd[0])) + + def programs(self, folder, names=setup.PROGRAMS + setup.MORE_PROGRAMS): + os.makedirs(os.path.join(self.root, folder), exist_ok=True) + for name in names: + with open(os.path.join(self.root, folder, name + (".exe" if os.name == "nt" else "")), "w"): + pass + + def listings(self, count): + folder = os.path.join(self.root, setup.FIXTURES) + os.makedirs(folder, exist_ok=True) + for i in range(count): + with open(os.path.join(folder, f"cs_{i}.s"), "w"): + pass + with open(os.path.join(folder, "README.txt"), "w"): + pass + + def survey(self, **kwargs): + return setup.survey(root=self.root, **kwargs) + + def levels(self, **kwargs): + return {level["level"]: level for level in self.survey(**kwargs)["levels"]} + + +class SurveyTest(SetupCase): + def test_nothing_but_python_runs_the_semantic_suite(self): + self.outputs.clear() + state = self.survey() + self.assertEqual((state["llvm_mc"], state["spirv_as"], state["spirv_val"], state["gpus"], state["build"], + state["listings"]), (None, None, None, [], None, 0)) + levels = {level["level"]: level for level in state["levels"]} + self.assertEqual((levels["semantic"]["ready"], levels["semantic"]["missing"]), (True, [])) + self.assertEqual(levels["semantic"]["command"], "python -I scripts/run_semantic_tests.py tests/semantic") + self.assertFalse(levels["subset"]["ready"] or levels["full"]["ready"]) + self.assertEqual(len(levels["subset"]["missing"]), 3) # programs, a device, the listings + self.assertEqual(len(levels["full"]["missing"]), 3) # programs, a device, llvm-mc + self.assertTrue(levels["full"]["missing"][2].startswith("llvm-mc: ")) + + def test_the_subset_needs_the_programs_a_device_and_the_listings_only(self): + self.programs("runtime/build") + self.listings(3) + state = self.survey() + self.assertEqual((state["build"], state["listings"]), (os.path.normpath("runtime/build"), 3)) + levels = {level["level"]: level for level in state["levels"]} + self.assertEqual((levels["subset"]["ready"], levels["subset"]["missing"]), (True, [])) + self.assertEqual(levels["subset"]["command"], "python -I scripts/run_gpu_tests.py --build runtime/build " + "--disasm-dir tests/semantic/fixtures/disasm") + # No llvm-mc and no SPIRV-Tools: the full run waits for llvm-mc alone. + self.assertEqual((levels["full"]["ready"], len(levels["full"]["missing"])), (False, 1)) + + def test_the_full_run_needs_an_llvm_mc_with_the_amdgpu_target(self): + self.programs("runtime/build") + self.listings(1) + self.on_path.add("llvm-mc") + self.outputs["llvm-mc"] = PLAIN + state = self.survey() + self.assertEqual(state["llvm_mc"], {"command": "llvm-mc", "version": "21.1.0", "amdgpu": False}) + full = state["levels"][2] + self.assertEqual((full["level"], full["ready"]), ("full", False)) + self.assertIn("an llvm-mc with the AMDGPU target: llvm-mc has none", full["missing"][0]) + self.outputs["llvm-mc"] = AMDGPU + state = self.survey() + self.assertEqual(state["llvm_mc"], {"command": "llvm-mc", "version": "23.1.6", "amdgpu": True}) + self.assertEqual((state["levels"][2]["ready"], state["levels"][2]["missing"]), (True, [])) + self.assertEqual(state["levels"][2]["command"], "python -I scripts/run_gpu_tests.py --build runtime/build") + + def test_the_full_run_needs_the_programs_its_texture_fixtures_start(self): + # The runner checks for three programs; the full run starts four more and fails their fixtures without. + self.programs("runtime/build", setup.PROGRAMS + ("vk_texture_test",)) + self.listings(1) + self.on_path.add("llvm-mc") + self.outputs["llvm-mc"] = AMDGPU + state = self.survey() + self.assertEqual(state["more_missing"], ["vk_bindless_test", "vk_sampler_test", "d3d12_texture_uav_test"]) + subset, full = state["levels"][1], state["levels"][2] + self.assertEqual((subset["ready"], full["ready"], len(full["missing"])), (True, False, 1)) + self.assertIn("vk_bindless_test, vk_sampler_test, d3d12_texture_uav_test in runtime/build", full["missing"][0]) + self.programs("runtime/build") + self.assertEqual((self.survey()["more_missing"], self.survey()["levels"][2]["ready"]), ([], True)) + + def test_the_printed_commands_work_as_printed(self): + # A build folder with a space is one argument, and an llvm-mc named only on this command line is passed on. + self.programs("gpu build") + self.listings(1) + self.outputs["wsl"] = AMDGPU + levels = self.levels(build="gpu build", raw_llvm_mc="wsl -e llvm-mc") + self.assertEqual(levels["subset"]["command"], 'python -I scripts/run_gpu_tests.py --build "gpu build" ' + "--disasm-dir tests/semantic/fixtures/disasm") + self.assertEqual(levels["full"]["command"], + 'python -I scripts/run_gpu_tests.py --build "gpu build" --llvm-mc "wsl -e llvm-mc"') + self.assertTrue(levels["full"]["ready"]) + # From LLVM_MC the runner reads it itself. + with mock.patch.dict(os.environ, {"LLVM_MC": "wsl -e llvm-mc"}): + self.assertEqual(self.levels(build="gpu build")["full"]["command"], + 'python -I scripts/run_gpu_tests.py --build "gpu build"') + + def test_llvm_mc_can_be_a_whole_command(self): + self.outputs["wsl"] = AMDGPU + mc = self.survey(raw_llvm_mc="wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc")["llvm_mc"] + self.assertEqual((mc["command"], mc["amdgpu"]), ("wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc", True)) + with mock.patch.dict(os.environ, {"LLVM_MC": "wsl -e llvm-mc"}): + self.assertEqual(self.survey()["llvm_mc"]["command"], "wsl -e llvm-mc") + + def test_the_programs_are_found_where_the_runner_looks(self): + self.listings(1) + self.programs("runtime/build/RelWithDebInfo") + self.assertEqual(self.survey()["build"], os.path.normpath("runtime/build/RelWithDebInfo")) + self.assertIn("--build runtime/build/RelWithDebInfo ", self.levels()["subset"]["command"]) + # Two of three is not a build. + self.programs("runtime/build/linux", setup.PROGRAMS[:2]) + self.assertEqual(self.survey(build="runtime/build/linux")["build"], None) + missing = self.levels(build="runtime/build/linux")["subset"]["missing"][0] + self.assertIn("vk_compute_test, vk_store_test, vk_harness in runtime/build/linux", missing) + other = os.path.join(self.root, "elsewhere", "Release") + self.programs(os.path.join("elsewhere", "Release")) + self.assertEqual(self.survey(build=os.path.join(self.root, "elsewhere"))["build"], os.path.normpath(other)) + + def test_spirv_tools_count_only_when_they_start(self): + self.on_path |= {"spirv-as", "spirv-val"} + self.assertEqual((self.survey()["spirv_as"], self.survey()["spirv_val"]), (None, None)) + self.outputs["spirv-as"] = "SPIRV-Tools v2026.4" + self.assertEqual((self.survey()["spirv_as"], self.survey()["spirv_val"]), ("spirv-as", None)) + + +class GpuTest(unittest.TestCase): + def test_devices_are_read_with_driver_and_subgroup_range(self): + self.assertEqual(setup.gpus(VULKANINFO), [ + {"name": "Vendor One 9000", "driver": "617.42", "subgroup": [32, 32]}, + {"name": "Vendor Two Graphics", "driver": "25.10.36 (proprietary)", "subgroup": [32, 64]}]) + self.assertEqual(setup.gpus("GPU0:\n\tdeviceName = Only\n"), [{"name": "Only", "driver": None, "subgroup": None}]) + self.assertEqual(setup.gpus(None), []) + self.assertEqual(setup.gpus("ERROR: no devices\n"), []) + + +class ReportTest(SetupCase): + def run_tool(self, *args): + out = io.StringIO() + with contextlib.redirect_stdout(out), mock.patch.object(setup, "ROOT", self.root): + code = setup.main(list(args)) + return code, out.getvalue() + + def test_text_report(self): + self.listings(2) + code, out = self.run_tool() + self.assertEqual(code, 0) + self.assertIn("llvm-mc: not found\n", out) + self.assertIn("spirv-as: not found (tools/spirv_asm.py assembles instead)\n", out) + self.assertIn("spirv-val: not found (validation is skipped)\n", out) + self.assertIn("programs: not built\nlistings: 2 in tests/semantic/fixtures/disasm\n", out) + self.assertIn("GPU: Vendor One 9000 (617.42), subgroup 32..32: wave64 fixtures need " + "LEONIDA_W64_EMULATE=1\n", out) + self.assertIn("GPU: Vendor Two Graphics (25.10.36 (proprietary)), subgroup 32..64\n", out) + self.assertIn("semantic: ready\n python -I scripts/run_semantic_tests.py tests/semantic\nsubset: not yet\n" + " needs the test programs", out) + self.assertNotIn("a second time", out) + self.programs("runtime/build") + self.on_path.add("llvm-mc") + self.outputs["llvm-mc"] = AMDGPU + out = self.run_tool()[1] + self.assertIn("llvm-mc: llvm-mc (23.1.6, AMDGPU target)\n", out) + self.assertIn("programs: runtime/build\n", out) + self.assertIn("subset: ready\n python -I scripts/run_gpu_tests.py --build runtime/build --disasm-dir", out) + self.assertIn("full: ready\n python -I scripts/run_gpu_tests.py --build runtime/build\n", out) + self.assertIn("run the GPU command a second time with LEONIDA_W64_EMULATE=1", out) + + def test_no_device_and_json(self): + self.outputs.clear() + self.assertIn("GPU: none reported by vulkaninfo\n", self.run_tool()[1]) + report = json.loads(self.run_tool("--json")[1]) + self.assertEqual(sorted(report), ["build", "gpus", "levels", "listings", "llvm_mc", "llvm_mc_option", "more_missing", "spirv_as", + "spirv_val"]) + self.assertEqual([level["level"] for level in report["levels"]], ["semantic", "subset", "full"]) + self.assertIn("a Vulkan device: vulkaninfo reports none", report["levels"][1]["missing"]) + + +class ThisRepositoryTest(unittest.TestCase): + def test_the_names_it_relies_on_are_the_runners(self): + with open(os.path.join(ROOT, "scripts", "run_gpu_tests.py"), encoding="utf-8") as f: + runner = f.read() + self.assertIn('REQUIRED_TEST_PROGRAMS = ("vk_compute_test", "vk_store_test", "vk_harness")', runner) + self.assertIn('"--disasm-dir"', runner) + self.assertTrue(os.path.isdir(os.path.join(ROOT, setup.FIXTURES))) + + +if __name__ == "__main__": + unittest.main()