diff --git a/docs/testing.md b/docs/testing.md index 8bb203ebd..64b42bd77 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -100,6 +100,14 @@ Actions -> Runtime, and check out the commit it built, or start a run of the com python -I scripts/run_gpu_tests.py --build ``` +If you also have neither `llvm-mc` nor SPIRV-Tools (`spirv-as` / `spirv-val`) installed, `--disasm-dir` runs the +pre-disassembled subset in `tests/semantic/fixtures/disasm` and `--assembler python` (the default under `auto` when +`spirv-as` is absent) assembles SPIR-V with `tools/spirv_asm.py`: + +```sh +python -I scripts/run_gpu_tests.py --build --disasm-dir tests/semantic/fixtures/disasm --assembler python +``` + `build.py` and `check.py` take the same folder as their second argument: ```sh diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index 75bf851cc..ff52a3f9b 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -129,7 +129,25 @@ def assemble_to_s(llvm_mc: str, asm_path: str, s_path: str, name: str) -> None: f.write("\n".join(lines) + "\n") -def spirv_as(asm_text: str, out_spv: str) -> None: +def resolve_assembler(choice: str) -> str: + """Resolve --assembler choice ('auto', 'spirv-as', or 'python') to a concrete assembler name.""" + if choice in ("spirv-as", "python"): + return choice + if choice == "auto": + return "spirv-as" if shutil.which("spirv-as") else "python" + raise ValueError(f"unknown assembler: {choice!r}") + + +def spirv_as(asm_text: str, out_spv: str, assembler: str = "spirv-as") -> None: + if assembler == "python": + import spirv_asm + try: + spv_bytes = spirv_asm.assemble(asm_text, target_env="vulkan1.2") + except spirv_asm.SpirvAsmError as exc: + raise RuntimeError(f"spirv_asm failed for {out_spv}:\n{exc}") from None + with open(out_spv, "wb") as f: + f.write(spv_bytes) + return p = subprocess.run(["spirv-as", "--target-env", "vulkan1.2", "-o", out_spv, "-"], input=asm_text, capture_output=True, text=True) if p.returncode != 0: @@ -699,12 +717,26 @@ def main() -> int: ap.add_argument("--work", default=None) ap.add_argument("--filter", default="") ap.add_argument("--require-pass", action="store_true", help="exit 1 if no GPU test passes") + ap.add_argument("--assembler", choices=("auto", "spirv-as", "python"), default="auto", + help="SPIR-V assembler: auto (use spirv-as if on PATH, else tools/spirv_asm.py), " + "spirv-as, or python") + ap.add_argument("--no-validate", action="store_true", + help="skip spirv-val during translation (automatic when --assembler resolves to python " + "and spirv-val is not on PATH)") + ap.add_argument("--disasm-dir", default=None, + help="folder of pre-disassembled .s listings (e.g. tests/semantic/fixtures/disasm); " + "skips llvm-mc and runs only fixtures present there") a = ap.parse_args() # Some test programs run with their working directory in /spirv (vk_texture_test), so a relative path # given here would point somewhere else for them. a.build = os.path.abspath(a.build) if a.work: a.work = os.path.abspath(a.work) + if a.disasm_dir is not None: + a.disasm_dir = os.path.abspath(a.disasm_dir) + if not os.path.isdir(a.disasm_dir): + print(f"error: --disasm-dir is not a directory: {a.disasm_dir}", file=sys.stderr) + return 2 ext = ".exe" if os.name == "nt" else "" required = tuple(t + ext for t in TEST_PROGRAMS) @@ -761,10 +793,24 @@ W64_GRAPHICS_ONLY = _w64_graphics_only() def run_suite(a, work: str) -> int: + assembler = resolve_assembler(getattr(a, "assembler", "auto")) + explicit_no_validate = bool(getattr(a, "no_validate", False)) + no_validate = explicit_no_validate or (assembler == "python" and shutil.which("spirv-val") is None) + disasm_src = getattr(a, "disasm_dir", None) + asm_files = sorted({f for f in os.listdir(SHADER_DIR) if f.endswith(".asm")} | {n + ".asm" for n in CLIP_CASES}) # The wave64 pixel fixtures of runtime/test/shaders/w64_graphics.py (tiers A-C, #1541) are checked by that # runner, not here: they need a 64-wide fragment subgroup or the halves-aware lowering it drives. asm_files = [f for f in asm_files if f[:-4] not in W64_GRAPHICS_ONLY] + if disasm_src is not None: + available = {os.path.splitext(f)[0] for f in os.listdir(disasm_src) if f.endswith(".s")} + asm_files = [ + f for f in asm_files + if all(os.path.splitext(p)[0] in available for p in with_draw_shaders([f])) + ] + if not asm_files: + print(f"error: --disasm-dir {disasm_src!r} matched no GPU test cases", file=sys.stderr) + return 2 if a.filter: asm_files = [f for f in asm_files if a.filter in f] if not asm_files: @@ -813,7 +859,10 @@ def run_suite(a, work: str) -> int: f.write(compute_header(os.path.join(SHADER_DIR, fname))) fname = shader_source(name) + ".asm" disasm_path = os.path.join(disasm_dir, f"{name}.s") - assemble_to_s(a.llvm_mc, os.path.join(SHADER_DIR, fname), disasm_path, name) + if disasm_src is not None: + shutil.copyfile(os.path.join(disasm_src, f"{name}.s"), disasm_path) + else: + assemble_to_s(a.llvm_mc, os.path.join(SHADER_DIR, fname), disasm_path, name) disasm_files.append(disasm_path) # A failed translation must not run an old binary left in a reused --work directory. Path(spirv_dir, f"{name}.spv").unlink(missing_ok=True) @@ -823,6 +872,12 @@ def run_suite(a, work: str) -> int: for path in disasm_files: shutil.copyfile(path, os.path.join(selected_disasm, os.path.basename(path))) cmd = [sys.executable, "-I", TRANSLATOR, selected_disasm, "--out", spirv_dir] + if assembler == "python": + cmd += ["--assembler", "python"] + if no_validate: + if not explicit_no_validate: + print("note: spirv-val not found on PATH; translating with --no-validate", flush=True) + cmd.append("--no-validate") if w64_emulated(): # wave64 compute/mesh exact on any subgroup size cmd.append("--wave64-emulate") if bary_fallback(): # raw barycentrics from an interpolated input, fed by a pass-through GS @@ -856,9 +911,9 @@ def run_suite(a, work: str) -> int: vs_tri = os.path.join(spirv_dir, "vs_tri.spv") fs_passthru = os.path.join(spirv_dir, "fs_passthru.spv") fs_loc1 = os.path.join(spirv_dir, "fs_loc1.spv") - spirv_as(VS_TRI_SPVASM, vs_tri) - spirv_as(make_fs_passthru(0), fs_passthru) - spirv_as(make_fs_passthru(1), fs_loc1) + spirv_as(VS_TRI_SPVASM, vs_tri, assembler=assembler) + spirv_as(make_fs_passthru(0), fs_passthru, assembler=assembler) + spirv_as(make_fs_passthru(1), fs_loc1, assembler=assembler) index = {} idx_path = os.path.join(spirv_dir, "index.json") diff --git a/tests/test_run_gpu_tests_python_assembler.py b/tests/test_run_gpu_tests_python_assembler.py new file mode 100644 index 000000000..0f66fd2f3 --- /dev/null +++ b/tests/test_run_gpu_tests_python_assembler.py @@ -0,0 +1,104 @@ +"""Tests for pure-Python SPIR-V assembly and --disasm-dir / --no-validate in run_gpu_tests.py and rdna2spirv.py.""" +import io +import json +import os +from pathlib import Path +import struct +import sys +import tempfile +import unittest +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "scripts")) +sys.path.insert(0, str(ROOT / "tools")) + +import rdna2spirv +import run_gpu_tests + + +class PythonAssemblerTests(unittest.TestCase): + def test_resolve_assembler_auto_and_explicit(self) -> None: + self.assertEqual(run_gpu_tests.resolve_assembler("python"), "python") + self.assertEqual(run_gpu_tests.resolve_assembler("spirv-as"), "spirv-as") + with patch.object(run_gpu_tests.shutil, "which", return_value="/usr/bin/spirv-as"): + self.assertEqual(run_gpu_tests.resolve_assembler("auto"), "spirv-as") + with patch.object(run_gpu_tests.shutil, "which", return_value=None): + self.assertEqual(run_gpu_tests.resolve_assembler("auto"), "python") + with self.assertRaises(ValueError): + run_gpu_tests.resolve_assembler("bogus") + + def test_spirv_as_python_assembles_helper_shaders(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + for name, src in ( + ("vs_tri.spv", run_gpu_tests.VS_TRI_SPVASM), + ("fs_passthru.spv", run_gpu_tests.make_fs_passthru(0)), + ): + out = Path(tmp) / name + run_gpu_tests.spirv_as(src, str(out), assembler="python") + data = out.read_bytes() + self.assertGreaterEqual(len(data), 20) + self.assertEqual(struct.unpack(" None: + with tempfile.TemporaryDirectory() as tmp: + spvasm = Path(tmp) / "fs_passthru.spvasm" + spv = Path(tmp) / "fs_passthru.spv" + asm = run_gpu_tests.make_fs_passthru(0) + with patch.object(rdna2spirv, "_run_spirv_tool", + side_effect=AssertionError("external spirv tool called")) as run_tool: + res = rdna2spirv.assemble_spirv(str(spvasm), str(spv), asm_text=asm, + assembler="python", validate=False) + run_tool.assert_not_called() + self.assertEqual(res.returncode, 0) + self.assertTrue(spv.is_file()) + self.assertEqual(struct.unpack(" None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + disasm = root / "disasm" + fssm = root / "fssm" + out = root / "out" + disasm.mkdir() + fssm.mkdir() + # Minimal valid compute listing (s_endpgm) and synthetic 0x148-byte FSSM header. + (disasm / "cs_noop.s").write_text("; synthetic\n\ts_endpgm\n", encoding="utf-8", newline="\n") + hdr = bytearray(0x148) + hdr[0:4] = b"FSSM" + struct.pack_into("<4I", hdr, 0x138, 0x8088, 64, 1, 1) + (fssm / "cs_noop.fssm").write_bytes(bytes(hdr)) + stdout = io.StringIO() + with patch("sys.stdout", stdout), \ + patch.object(sys, "argv", [ + "rdna2spirv.py", str(disasm), "--out", str(out), "--assembler", "python", "--no-validate", + ]), \ + patch.object(rdna2spirv, "_run_spirv_tool", + side_effect=AssertionError("external spirv tool called")): + rc = rdna2spirv.main() + self.assertIn(rc, (0, None)) + self.assertIn("1 shaders: 1 translated, 1 assembled (spirv-val skipped)", stdout.getvalue()) + spv = out / "cs_noop.spv" + self.assertTrue(spv.is_file()) + self.assertEqual(struct.unpack(" None: + with tempfile.TemporaryDirectory() as tmp: + build = Path(tmp) / "build" + build.mkdir() + ext = ".exe" if os.name == "nt" else "" + for prog in run_gpu_tests.TEST_PROGRAMS: + (build / (prog + ext)).write_bytes(b"") + missing = Path(tmp) / "no_such_disasm" + err = io.StringIO() + with patch("sys.stderr", err), \ + patch.object(sys, "argv", ["run_gpu_tests.py", "--build", str(build), "--disasm-dir", str(missing)]): + rc = run_gpu_tests.main() + self.assertEqual(rc, 2) + self.assertIn("--disasm-dir is not a directory", err.getvalue()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 657df2d18..8a9963e00 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -17528,12 +17528,13 @@ def _run_spirv_tool(cmd, **kwargs): raise -def assemble_spirv(sa, sv, asm_text=None, assembler="spirv-as"): +def assemble_spirv(sa, sv, asm_text=None, assembler="spirv-as", validate=True): """Keep the assembled module out of the final path until validation succeeds. `assembler="spirv-as"` invokes the external spirv-as binary on `sa` (default); `assembler="python"` encodes `asm_text` (or reads `sa`) directly in memory with tools/spirv_asm.py, avoiding the spirv-as subprocess and temporary .spvasm I/O. + When `validate=False`, skip running `spirv-val` after assembly. """ with tempfile.NamedTemporaryFile(prefix=".spirv-", suffix=".tmp", dir=os.path.dirname(sv), delete=False) as f: tmp = Path(f.name) @@ -17564,7 +17565,7 @@ def assemble_spirv(sa, sv, asm_text=None, assembler="spirv-as"): result.stdout = result.stdout.decode("utf-8", "replace") if isinstance(result.stderr, bytes): result.stderr = result.stderr.decode("utf-8", "replace") - if result.returncode == 0: + if result.returncode == 0 and validate: # Offset on non-gather: VK_KHR_maintenance8 result = _run_spirv_tool(["spirv-val", "--target-env", "vulkan1.2", "--allow-offset-texture-operand", tmp.name], capture_output=True, text=True, cwd=folder) @@ -17638,6 +17639,9 @@ def main(): ap.add_argument("--assembler", choices=("spirv-as", "python"), default="spirv-as", help="SPIR-V binary assembler: spirv-as (default, external binary) or python (in-process " "tools/spirv_asm.py; skips writing .spvasm to disk when combined with --no-asm)") + ap.add_argument("--no-validate", action="store_true", + help="skip spirv-val after assembly (for running GPU tests without SPIRV-Tools when paired " + "with --assembler python)") ap.add_argument("--merge", action="store_true", help="merge index.part*.json in --out into index.json and exit") ap.add_argument("--fssm-dir", default=None, help="optional dir with .fssm sidecars: records fssm_sha256 per shader in the index") @@ -17828,7 +17832,7 @@ def main(): with open(sa, "w", encoding="utf-8", newline="\n") as f: f.write(asm) try: - r = assemble_spirv(sa, sv, asm_text=asm, assembler=a.assembler) + r = assemble_spirv(sa, sv, asm_text=asm, assembler=a.assembler, validate=not a.no_validate) except OSError as e: # A missing spirv-as/spirv-val fails every shader the same way; report it once as a setup # error (exit 2) instead of a FileNotFoundError traceback from the first one. @@ -17881,7 +17885,8 @@ def main(): if shard is None: import spirv_stubs spirv_stubs.generate_for_index(a.out, old) - print(f"{len(files)} shaders: {ok} translated, {valid} pass spirv-val") + status_label = "assembled (spirv-val skipped)" if a.no_validate else "pass spirv-val" + print(f"{len(files)} shaders: {ok} translated, {valid} {status_label}") if W64G_COUNTS: print("wave64 VS/PS/GS on 32-wide subgroups: " + ", ".join(f"tier {t}: {n}" for t, n in sorted(W64G_COUNTS.items())) + (" (tier C is not exact there; see wave64_graphics_reasons in the index)" if W64G_COUNTS["C"] else ""))