diff --git a/docs/design.md b/docs/design.md index 7888e24f72..87a704e62e 100644 --- a/docs/design.md +++ b/docs/design.md @@ -421,7 +421,7 @@ How the generated SPIR-V expects the runtime to work: | Barycentric fallback (`--bary-fallback`) | For devices without `VK_KHR_fragment_shader_barycentric` (NVIDIA Pascal, for one), and for Mesa ANV's known BaryCoordKHR.i bug (SHADER-925). The raw pair a PS reads comes from an ordinary vec3 input, `%bary`, at the lowest location none of the shader's attributes uses, instead of `BuiltIn BaryCoordKHR`. The module needs neither the `FragmentBarycentricKHR` capability nor the extension, and the index records the location as `bary_fallback_input`. `tools/bary_fallback_gs.py` writes a pass-through geometry shader that supplies (1,0,0), (0,1,0), (0,0,1) at the triangle vertices. GPU-checked on NVIDIA Pascal and Intel Arc B580/Mesa ANV: ANV native `ps_uniform_branch` and `ps_scc_mask32` fail with i=0.0, while the fallback passes and `ps_bary` passes natively. `make_game.py` and `scripts/run_gpu_tests.py` select the fallback automatically for Mesa ANV. `LEONIDA_BARY_FALLBACK=1` forces fallback and `LEONIDA_BARY_FALLBACK=0` forces native barycentrics consistently in both entry points; explicit `--bary-fallback` also forces the fallback in `make_game.py`. The standalone `build.py`/`check.py` path follows the same variable/probe rule. Checked in `tests/semantic/test_bary_fallback.py` and the builder/runner wiring tests. | | Metadata index | `spirv/index.json`: one entry per translated shader with its stage, `wave64` / `subgroup_size`, SPIR-V capabilities and extensions, the Vulkan **features** to enable (barycentrics, interlock, mesh, geometry, Float64, Int64, buffer device address, write-without-format, `shaderFmaFloat32` for `--fma khr`, …), `needs_maintenance8`, the descriptor bindings it uses (set 0), push-constant size, `local_size`, `user_sgprs` (CS), `lds_bytes`, mesh `max_vertices`/`max_primitives`/`params`, geometry inputs/outputs, vertex-input locations and types, full `vertex_input_signature` (ISG1 register/mask/system-value/component-type, for PSO lookup), `wave64_emulated` (true for VS/PS/GS wave64, which the translator emits as per-subgroup code with no cross-half exchange, and for compute/mesh translated with `--wave64-emulate`; the runtime does not use it: it reads `wave64`, `subgroup_size` and `wave64_exchange`), `dynamic_format` (runtime V# FORMAT: codes outside FORMATS decode to 0) / `fixed_format_codes`, `src_sha256` and optional `fssm_sha256` (via `--fssm-dir`), PS system inputs, `bary_fallback_input` (`--bary-fallback`: the location of the barycentric input), `mesh_compute` (`--mesh-compute`: the slot layout and push-constant size), `pc_tail` (`--pc-tail-ubo`: the set, binding and size of the uniform block that holds the push-constant tail), and input/output locations. A shader translated with `--wave64-emulate` carries `wave64_exchange: "workgroup"` and `subgroup_size: null`: any subgroup size is exact, request none. Otherwise `subgroup_size` (64 for wave64, 32) is what the PSO asks for through `VkPipelineShaderStageRequiredSubgroupSizeCreateInfo` where the device lists the stage in `requiredSubgroupSizeStages` (docs/d3d12_vulkan.md section 3.2): that list is the driver's, not "compute/mesh only". The AMD Windows driver reports FRAGMENT, COMPUTE, TASK and MESH (measured on a Radeon 880M, driver 26.11.2, sizes 32..64), and current Mesa RADV on GFX10+ reports COMPUTE, FRAGMENT and task/mesh (`src/amd/vulkan/radv_physical_device.c`, `requiredSubgroupSizeStages`, Mesa main at 152b9cde; older Mesa: compute only), so wave64 pixel shaders can run exact there. NVIDIA lists every stage but only size 32, so there a native wave64 shader cannot get 64 and wave64 PS/VS/GS stay 2x32. A runtime can create every pipeline at load time from it without parsing SPIR-V. | | Full-corpus pipeline build | `vk_pipeline_check pipeline_cache.bin --jobs 4` on an RTX 4060 Ti (NVIDIA 595 driver): **all 26,503 shaders become real pipelines, 0 failures** (cs 2,689, ps 12,101, ms 9,282, vs 2,236, gs 195; graphics stages with generated stub partners). Compile time 40,784 s of CPU (2.84 h wall on 4 threads): cs 23,633 s (mean 8.8 s; the ray-tracing ScreenProbes/RTShadowTrace shaders take 2-19 min each), ps 11,481 s, ms 5,395 s, vs 275 s. The resulting `VkPipelineCache` is 3.81 GB; seeding a run with it makes those pipelines instant, which is what a fast first boot needs. The cache is per driver and GPU, and a shader whose SPIR-V changes compiles again (the checker resumes from the file). Neither register storage (one variable per register) nor smaller SPIR-V cut NVIDIA compile time: the big ray-tracing shaders are expensive as such, so the runtime should compile them in the background rather than block on them. | -| `v_cndmask_b32` source modifiers | `v_cndmask_b32` only moves bits, so a VOP3 `abs` on `src0`/`src1` clears bit 31 and `neg` flips it (`abs` first) as plain bit moves (`OpBitwiseAnd 0x7FFFFFFF`, then `OpBitwiseXor 0x80000000`, `Gen.src_u_sign_mods`), never `FAbs`/`OpFNegate`: a signalling NaN stays signalling and a denormal isn't flushed. Until 2026-11-23 the sources went through `Gen.modify`, and the mini interpreter quieted them (`-v1` of `0x7F800001` gave `0xFFC00001`, not `0xFF800001`). **Not measured on hardware for this instruction**: the rule follows the same VOP3 input modifiers measured as sign-bit moves on `v_cmp_class_f32` (gfx1036, all four IEEE/denorm modes, row "Floating-point class compare" above), and LLVM's AMDGPU backend moves `fneg`/`fabs` through a select into `v_cndmask_b32_e64`'s source modifiers (`AMDGPUTargetLowering::foldFreeOpFromSelect`), which is only exact if they are sign-bit moves. Checked on the CPU and with `spirv-val` by `tests/semantic/test_cndmask_sign_mods.py` (15 words including signalling/quiet NaNs, denormals, zeros and infinities x `v`, `-v`, `\|v\|`, `-\|v\|` x both operands). | +| `v_cndmask_b32` source modifiers | `v_cndmask_b32` only moves bits, so a VOP3 `abs` on `src0`/`src1` clears bit 31 and `neg` flips it (`abs` first) as plain bit moves (`OpBitwiseAnd 0x7FFFFFFF`, then `OpBitwiseXor 0x80000000`, `Gen.src_u_sign_mods`), never `FAbs`/`OpFNegate`: a signalling NaN stays signalling and a denormal isn't flushed. Until 2026-11-23 the sources went through `Gen.modify`, and the mini interpreter quieted them (`-v1` of `0x7F800001` gave `0xFFC00001`, not `0xFF800001`). **Measured on RDNA3**: on an AMD Radeon RX 7800 XT (gfx1101, Windows driver 32.0.32029.2010) through `tools/hw_oracle`, `tools/cndmask_hw_probe.py` gives sign-bit moves for all 120 results (the 15 words of the test below x `v`, `-v`, `\|v\|`, `-\|v\|` x both operands) in wave32 and wave64 under all four `ieee` 0/1 x `denorm32` 0/3 modes, while a `v_add_f32` and a `v_mul_f32` in the same kernels flush a denormal and quiet a signalling NaN exactly where the mode says ([result](https://github.com/ubiquitarianism/leonida/issues/1608#issuecomment-7161680445)). **Not measured on RDNA2**; the same command runs it on a gfx103x card. Before that measurement the rule rested on two arguments. It follows the same VOP3 input modifiers measured as sign-bit moves on `v_cmp_class_f32` (gfx1036, all four IEEE/denorm modes, row "Floating-point class compare" above), and LLVM's AMDGPU backend moves `fneg`/`fabs` through a select into `v_cndmask_b32_e64`'s source modifiers (`AMDGPUTargetLowering::foldFreeOpFromSelect`), which is only exact if they are sign-bit moves. Checked on the CPU and with `spirv-val` by `tests/semantic/test_cndmask_sign_mods.py` (15 words including signalling/quiet NaNs, denormals, zeros and infinities x `v`, `-v`, `\|v\|`, `-\|v\|` x both operands). | | Wave-uniform branches | VCC and EXEC are wave-wide registers, but one invocation holds only its own lane's bit. `s_cbranch_vccz/vccnz/execz/execnz` therefore reduce the condition across the subgroup (`OpGroupNonUniformAny`), so the whole wave takes the branch together, as on hardware. Before this, each lane decided alone. A lane could skip scalar instructions that the hardware wave executes (its SGPRs went stale for later code), and cross-lane ops or barriers inside the block saw a split wave. `v_cmp`/`v_cmp_class`/64-bit compares now write 0 for inactive lanes (hardware VOPC behaviour), so the reduction sees the true mask. GPU-checked with `runtime/test/shaders/ps_uniform_branch.asm`: lanes whose own VCC bit is 0 run the block's scalar add when their wave has any set bit. `s_cbranch_scc0/1` stay per lane; SCC is uniform as long as the SGPRs feeding it are. | | Compute shaders | FSSM header word **0x138 = `COMPUTE_PGM_RSRC2`**: USER_SGPR [5:1], TGID_X/Y/Z_EN [9:7], TG_SIZE_EN [10], TIDIG_COMP_CNT [12:11], LDS_SIZE [23:15] in 512-byte units. Words **0x13C/0x140/0x144 = thread-group size**. Counted over all 2,689 CS listings of 1.0.2.1 by the SGPRs each reads before writing (operand roles from `shader_meta._split_operands`, over the code `translate()` keeps; in wave64 code a lane mask printed as one SGPR covers the pair; an earlier check gave 2,281 exact): 2,540 read nothing past the user SGPRs and enabled TGIDs (2,193 up to the last of them, 342 fewer, 5 none), and the other 149 overshoot only through loop-carried registers in the straight-line check: every extra read follows a branch, and the register is written later in program order. Followed through the CFG (written on every path before the read), 22 still overshoot; each extra register is written on some other path (only loop-carried ones in 15), so these are values undefined on some path, not a missing input. Read raw, 268 overshoot: the other 119 are listings with embedded data words, decoded as instructions. 0x110, which looked similar, doesn't match. Layout: s0..user−1 = user data (push constants), then the enabled workgroup IDs (`WorkgroupId`), and v0/v1/v2 = thread ID x/y/z (`LocalInvocationId`, separate VGPRs on GFX10). Example: the 1,013 shaders with RSRC2 `0x998` have 12 user SGPRs, group ID x/y in s12/s13, and compute x = s12·32 + v0. With TG_SIZE_EN (none of the 2,689; 91 compute programs of the pipeline library, [shader_library.md](shader_library.md)) the next SGPR is the thread-group word, which the prologue writes: the number of waves in the group in bits [5:0] and this wave's index in it in bits [11:6], the wave index again in bits [24:20] and bit 31 set in the group's first wave (measured on gfx1036 through `tools/hw_oracle`, #6446: wave32 x 128 threads gives `80000004 00100044 00200084 003000c4`; one library program reads [24:20]; not measured on gfx1013) (Mesa `ac_nir_lower_intrinsics_to_args.c`, GFX6-10: `load_num_subgroups` and `load_subgroup_id` read those fields, and a wave64 compute shader's local invocation index is `mbcnt(~0, tg_size & 0xfc0)`; the library programs read it as `s_and_b32 sN, sTG, 0xfc0`, most of them then `v_mbcnt_lo_u32_b32`). Thread i is in wave i / W, as for `s_get_waveid_in_workgroup`. CPU-checked by `tests/semantic/test_cs_tg_size.py`, including the gfx1036 words. GPU-checked with `runtime/test/shaders/cs_lds.asm` through `runtime/test/vk_compute_test.cpp`: 4 groups × 64 threads, LDS exchange between the two waves of a group behind `s_barrier`, store through a V# into the device-address heap, 0 mismatches. | | Scalar copies through VCC | SGPRs 106 and 107 can hold two data words, including a buffer descriptor's count and format. A 64-bit move through VCC preserves both when its reads within the block use them as data. Predicate users and live-out VCC constrain this inference. A wide scalar load into a tuple ending in VCC writes both physical words. The synthetic descriptor fixture checks numeric copies, a round trip, and a subsequent tuple load on wave32 and emulated wave64. | diff --git a/tests/test_cndmask_hw_probe.py b/tests/test_cndmask_hw_probe.py new file mode 100644 index 0000000000..692d0d2922 --- /dev/null +++ b/tests/test_cndmask_hw_probe.py @@ -0,0 +1,259 @@ +"""CPU-only unit tests for tools/cndmask_hw_probe.py (TOOL-CNDMASK-HW-PROBE). No GPU and no game files. + +The assembler test runs AMD clang's llvm-mc when LEONIDA_AMD_CLANG points at a clang.exe with llvm-mc beside it, and +is skipped otherwise. +""" +import io +import json +import os +import shutil +import subprocess +import sys +import tempfile +import types +import unittest +from unittest import mock + +REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +TOOLS = os.path.join(REPO, "tools") +PROBE = os.path.join(TOOLS, "cndmask_hw_probe.py") +if TOOLS not in sys.path: + sys.path.insert(0, TOOLS) + +import cndmask_hw_probe as probe # noqa: E402 + + +class _FakeUnavailable(Exception): + pass + + +def _fake_hw_oracle(open_side_effect=None, family="gfx11", mode_skip=None): + def fam(arch): + if family is None: + raise ValueError(arch) + return family + asm_mod = types.SimpleNamespace(family=fam, Kernel=lambda *a, **k: (a, k), + mode_skip_reason=lambda mode, arch: mode_skip) + open_oracle = mock.Mock(side_effect=open_side_effect or _FakeUnavailable("no gpu")) + runner_mod = types.SimpleNamespace(Unavailable=_FakeUnavailable, open_oracle=open_oracle) + pkg = types.SimpleNamespace(asm=asm_mod, runner=runner_mod) + return {"hw_oracle": pkg, "hw_oracle.asm": asm_mod, "hw_oracle.runner": runner_mod}, open_oracle + + +def _words(ieee, denorm32, quiet_snan=False, flush_denormals=False, control_off=None): + """The words a GPU stores for one kernel: sign-bit moves, optionally quieting or flushing them, and the + controls of the given MODE; control_off= breaks one control.""" + out = [] + for w, _, mod, _ in probe.runs(): + g = probe.bit_move(w, mod) + exp, frac = (g >> 23) & 0xFF, g & 0x7FFFFF + if quiet_snan and exp == 0xFF and frac and not frac & 0x400000: + g |= 0x400000 + if flush_denormals and exp == 0 and frac: + g &= 0x80000000 + out.append(g) + ctl = [probe.control_expected(name, ieee, denorm32) for name, _, _ in probe.CONTROLS] + if control_off is not None: + ctl[control_off] ^= 1 + return out + ctl + + +class Model(unittest.TestCase): + def test_self_test_passes(self): + with mock.patch.object(sys, "stdout", io.StringIO()): + probe.self_test() + + def test_bit_move_is_abs_then_neg(self): + self.assertEqual(probe.bit_move(0xFF800001, "-|v|"), 0xFF800001) + self.assertEqual(probe.bit_move(0x7F800001, "-|v|"), 0xFF800001) + self.assertEqual(probe.bit_move(0xFF800001, "-v"), 0x7F800001) + self.assertEqual(probe.bit_move(0x80000001, "|v|"), 0x00000001) + self.assertEqual(probe.bit_move(0x12345678, "v"), 0x12345678) + + def test_classify_names_each_float_effect(self): + self.assertEqual(probe.classify(0x7FA00000, "v", 0x7FE00000), "quieted") + self.assertEqual(probe.classify(0x007FFFFF, "-v", 0x80000000), "flushed") + self.assertEqual(probe.classify(0x7FC00000, "v", 0x7FC00000), "bit_move") + # a quiet NaN cannot be "quieted", and a wrong sign is not a flush + self.assertEqual(probe.classify(0xFFC00001, "|v|", 0x7FC00001), "bit_move") + self.assertEqual(probe.classify(0x00000001, "-v", 0x00000000), "other") + + def test_runs_cover_every_word_mod_and_side_once(self): + runs = probe.runs() + self.assertEqual(len(runs), len(set((w, m, s) for w, _, m, s in runs))) + self.assertEqual({w for w, _, _, _ in runs}, {w for w, _ in probe.WORDS}) + self.assertEqual({m for _, _, m, _ in runs}, {m for m, _ in probe.MODS}) + self.assertEqual({s for _, _, _, s in runs}, set(probe.SIDES)) + + def test_kernel_lines_store_each_result_at_its_own_offset(self): + for wave in (32, 64): + with self.subTest(wave=wave): + lines = probe.kernel_lines(wave) + offsets = [int(ln.rsplit("offset:", 1)[1]) for ln in lines if ln.startswith("global_store_b32")] + self.assertEqual(offsets, [4 * i for i in range(probe.words_per_kernel())]) + cond = "s4" if wave == 32 else "s[4:5]" + cnd = [ln for ln in lines if ln.startswith("v_cndmask_b32_e64")] + self.assertEqual(len(cnd), len(probe.runs())) + self.assertTrue(all(ln.endswith(", " + cond) for ln in cnd)) + self.assertEqual(any(ln.startswith("s_mov_b32 s5") for ln in lines), wave == 64) + with self.assertRaises(ValueError): + probe.kernel_lines(16) + + def test_the_selected_source_is_the_modified_one(self): + lines = probe.kernel_lines(32) + for k, (w, _, mod, side) in enumerate(probe.runs()): + cnd = [ln for ln in lines if ln.startswith("v_cndmask_b32_e64")][k] + src0, src1 = [t.strip() for t in cnd.split(",")[1:3]] + with self.subTest(k=k): + self.assertEqual("v1" in src0, side == "src0") + self.assertEqual("v1" in src1, side == "src1") + + def test_controls_tell_every_mode_apart(self): + seen = {tuple(probe.control_expected(n, i, d) for n, _, _ in probe.CONTROLS) for i, d in probe.MODES} + self.assertEqual(len(seen), len(probe.MODES)) + with self.assertRaises(ValueError): + probe.control_expected("other", 0, 0) + + +@unittest.skipUnless(os.environ.get("LEONIDA_AMD_CLANG") and shutil.which( + os.path.join(os.path.dirname(os.environ.get("LEONIDA_AMD_CLANG", "")), "llvm-mc")), + "needs LEONIDA_AMD_CLANG with llvm-mc beside it") +class LlvmMcAssembles(unittest.TestCase): + """Every kernel body assembles for gfx1030 (in GFX10 spelling) and gfx1101, in both wave sizes.""" + + def test_kernel_lines_assemble(self): + from hw_oracle import asm + mc = shutil.which(os.path.join(os.path.dirname(os.environ["LEONIDA_AMD_CLANG"]), "llvm-mc")) + for cpu in ("gfx1030", "gfx1101"): + for wave in (32, 64): + lines = probe.kernel_lines(wave) + if cpu == "gfx1030": + lines = [asm.gfx10_spelling(ln) for ln in lines] + with self.subTest(cpu=cpu, wave=wave): + r = subprocess.run([mc, "-arch=amdgcn", f"-mcpu={cpu}", f"-mattr=+wavefrontsize{wave}", + "--show-encoding"], input="\n".join(lines) + "\n", capture_output=True, + text=True, check=False) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertNotIn("error", r.stderr) + self.assertEqual(r.stdout.count("v_cndmask_b32_e64"), len(probe.runs())) + + +class Judging(unittest.TestCase): + def test_sign_bit_moves_with_their_mode_pass(self): + for ieee, den in probe.MODES: + with self.subTest(ieee=ieee, denorm32=den): + entry = probe.judge(32, ieee, den, _words(ieee, den)) + self.assertEqual(entry["counts"]["bit_move"], len(probe.runs())) + self.assertTrue(entry["controls_ok"]) + self.assertTrue(probe.report_ok([entry])) + + def test_float_behaviour_is_counted_and_fails(self): + entry = probe.judge(64, 1, 0, _words(1, 0, quiet_snan=True, flush_denormals=True)) + self.assertEqual(entry["counts"]["quieted"], 3 * len(probe.MODS) * len(probe.SIDES)) + self.assertEqual(entry["counts"]["flushed"], 3 * len(probe.MODS) * len(probe.SIDES)) + self.assertFalse(probe.report_ok([entry])) + self.assertIn("quieted", probe.describe(entry)) + + def test_a_control_that_does_not_show_its_mode_fails(self): + for i in range(len(probe.CONTROLS)): + with self.subTest(control=i): + entry = probe.judge(32, 0, 3, _words(0, 3, control_off=i)) + self.assertFalse(entry["controls_ok"]) + self.assertFalse(probe.report_ok([entry])) + self.assertIn("MODE NOT SHOWN", probe.describe(entry)) + + def test_a_short_result_is_a_harness_error(self): + with self.assertRaises(RuntimeError): + probe.judge(32, 0, 0, _words(0, 0)[:-1]) + + +class Cli(unittest.TestCase): + def run_main(self, argv, modules): + stdout, stderr = io.StringIO(), io.StringIO() + with mock.patch.dict(sys.modules, modules), mock.patch.object(sys, "stdout", stdout), \ + mock.patch.object(sys, "stderr", stderr): + rc = probe.main(argv) + return rc, stdout.getvalue(), stderr.getvalue() + + def test_missing_oracle_exits_77(self): + env = {k: v for k, v in os.environ.items() if not k.startswith("LEONIDA_HW_") and k != "LEONIDA_AMD_CLANG"} + env["LEONIDA_AMD_CLANG"] = os.path.join(REPO, "does_not_exist_clang") + proc = subprocess.run([sys.executable, "-I", PROBE], env=env, capture_output=True, text=True, check=False) + self.assertEqual(proc.returncode, 77, proc.stderr or proc.stdout) + + def test_self_test_flag(self): + proc = subprocess.run([sys.executable, "-I", PROBE, "--self-test"], capture_output=True, text=True, + check=False) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertIn("self-test OK", proc.stdout) + + def test_bad_arguments_are_rejected_before_the_oracle_opens(self): + modules, open_oracle = _fake_hw_oracle() + for argv in (["--waves", ""], ["--waves", "16"], ["--waves", "32,x"], ["--json", ""], + ["--json", "bad\x00.json"]): + with self.subTest(argv=argv): + rc, _, err = self.run_main(argv, modules) + self.assertEqual(rc, 2) + self.assertIn("error:", err) + open_oracle.assert_not_called() + + def test_json_path_that_is_a_directory_is_rejected(self): + modules, open_oracle = _fake_hw_oracle() + with tempfile.TemporaryDirectory() as tmp: + rc, _, _ = self.run_main(["--json", tmp], modules) + self.assertEqual(rc, 2) + open_oracle.assert_not_called() + + def test_gpus_that_cannot_set_the_mode_skip_with_77_and_close_the_oracle(self): + for family, mode_skip in (("gfx12", None), (None, None), ("gfx11", "ieee cannot be set on gfx1170")): + oracle = types.SimpleNamespace(arch="gfx1201", close=mock.Mock()) + modules, _ = _fake_hw_oracle(open_side_effect=lambda: oracle, family=family, mode_skip=mode_skip) + with self.subTest(family=family, mode_skip=mode_skip): + rc, _, err = self.run_main([], modules) + self.assertEqual(rc, 77) + self.assertIn("SKIP", err) + oracle.close.assert_called_once() + + def test_run_writes_the_report_and_exit_code_follows_it(self): + def oracle_for(**kw): + return types.SimpleNamespace( + arch="gfx1101", close=mock.Mock(), + run=lambda ks: [_words(k[1]["mode"]["ieee"], k[1]["mode"]["denorm32"], **kw) for k in ks]) + good = oracle_for() + modules, _ = _fake_hw_oracle(open_side_effect=lambda: good) + with tempfile.TemporaryDirectory() as tmp: + out = os.path.join(tmp, "sub", "report.json") + rc, stdout, _ = self.run_main(["--waves", "32", "--json", out], modules) + self.assertEqual(rc, 0, stdout) + self.assertIn("every source modifier is a sign-bit move", stdout) + self.assertEqual(stdout.count("120/120 sign-bit moves"), len(probe.MODES)) + with open(out, "rb") as f: + raw = f.read() + self.assertNotIn(b"\r\n", raw) + data = json.loads(raw) + self.assertEqual((data["arch"], data["ok"], len(data["kernels"])), ("gfx1101", True, len(probe.MODES))) + good.close.assert_called_once() + bad = oracle_for(quiet_snan=True) + modules, _ = _fake_hw_oracle(open_side_effect=lambda: bad) + rc, stdout, _ = self.run_main(["--waves", "64"], modules) + self.assertEqual(rc, 1) + self.assertIn("NOT every result", stdout) + + def test_a_failed_kernel_is_a_harness_error(self): + oracle = types.SimpleNamespace(arch="gfx1101", close=mock.Mock(), + run=lambda kernels: ["assembler rejected: x"] * len(kernels)) + modules, _ = _fake_hw_oracle(open_side_effect=lambda: oracle) + rc, _, err = self.run_main(["--waves", "32"], modules) + self.assertEqual(rc, 2) + self.assertIn("assembler rejected", err) + oracle.close.assert_called_once() + + def test_write_json_report_error_is_one_line(self): + with tempfile.TemporaryDirectory() as tmp: + with mock.patch("builtins.open", side_effect=PermissionError(13, "denied")): + err = probe.write_json_report(os.path.join(tmp, "out.json"), {}) + self.assertIn("cannot write --json", err) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/cndmask_hw_probe.py b/tools/cndmask_hw_probe.py new file mode 100644 index 0000000000..f671dd3f59 --- /dev/null +++ b/tools/cndmask_hw_probe.py @@ -0,0 +1,302 @@ +r"""Measure the VOP3 source modifiers of `v_cndmask_b32` natively through `tools/hw_oracle` (TOOL-CNDMASK-HW-PROBE). + +Are `abs` / `neg` on `v_cndmask_b32_e64`'s sources sign-bit moves (`abs` clears bit 31, `neg` then flips it), or +float operations that quiet a signalling NaN or flush a denormal? The translator emits sign-bit moves +(`Gen.src_u_sign_mods` in `tools/rdna2spirv.py`); this is the "`v_cndmask_b32` source modifiers" row of +docs/design.md. Measured on an RX 7800 XT (gfx1101): sign-bit moves in every mode. + +Each kernel runs one lane. Every word of WORDS goes through `v`, `-v`, `|v|` and `-|v|`, as the selected src0 +(condition 0) and as the selected src1 (condition all ones); the other source is 0x12345678. There is one kernel per +wave size and MODE (`ieee` 0/1 x `denorm32` 0/3). Each kernel also stores two float ops as controls that show its +MODE is in effect: `v_add_f32(+min denormal, 0)` is flushed exactly when denorm32 = 0, and +`v_mul_f32(sNaN, 1.0)` is quieted exactly when ieee = 1. + +Usage: + python -I tools/cndmask_hw_probe.py [--waves 32,64] [--json out.json] + python -I tools/cndmask_hw_probe.py --self-test # model checks, no GPU + +Exit 0 when every result is a sign-bit move and every control shows its MODE (or --self-test passed), 1 when one is +not or the report cannot be written, 2 on a harness or CLI error, 77 when tools/hw_oracle is unavailable or the GPU +cannot set these MODEs (not gfx10 / gfx11, or gfx1170 and later). Standard library only; nothing here reads game +files. +""" +import argparse +import json +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.dont_write_bytecode = True +if HERE not in sys.path: + sys.path.insert(0, HERE) + +FAMILIES = ("gfx10", "gfx11") +WORDS = ( + (0x00000000, "+0"), (0x80000000, "-0"), (0x00000001, "+min denormal"), (0x80000001, "-min denormal"), + (0x007FFFFF, "+max denormal"), (0x3F800000, "+1.0"), (0xC0000000, "-2.0"), (0x7F7FFFFF, "+max normal"), + (0x7F800000, "+inf"), (0xFF800000, "-inf"), (0x7FC00000, "+qNaN"), (0xFFC00001, "-qNaN payload 1"), + (0x7F800001, "+sNaN payload 1"), (0xFF800001, "-sNaN payload 1"), (0x7FA00000, "+sNaN payload 0x200000"), +) +MODS = (("v", "{}"), ("-v", "-{}"), ("|v|", "|{}|"), ("-|v|", "-|{}|")) +SIDES = ("src0", "src1") +OTHER = 0x12345678 +MODES = tuple((ieee, den) for ieee in (0, 1) for den in (0, 3)) +# (name, input word, instruction writing v3 from v1) +CONTROLS = ( + ("denorm_add", 0x00000001, "v_add_f32_e64 v3, v1, 0"), + ("snan_mul", 0x7F800001, "v_mul_f32_e64 v3, v1, 1.0"), +) +CLASSES = ("bit_move", "quieted", "flushed", "other") + + +def runs(): + """(word, name, mod, side) for every result a kernel stores before its controls.""" + return [(w, name, mod, side) for w, name in WORDS for mod, _ in MODS for side in SIDES] + + +def kernel_lines(wave): + """The raw kernel body (GFX11 spelling; hw_oracle renames the stores for GFX10).""" + if wave not in (32, 64): + raise ValueError(f"wave size {wave} is not 32 or 64") + cond = "s4" if wave == 32 else "s[4:5]" + fmt = dict(MODS) + body = ["v_mov_b32_e32 v10, 0", f"v_mov_b32_e32 v2, 0x{OTHER:08x}"] + for k, (w, _, mod, side) in enumerate(runs()): + sel = -1 if side == "src1" else 0 + body += [f"v_mov_b32_e32 v1, 0x{w:08x}", f"s_mov_b32 s4, {sel}"] + if wave == 64: + body.append(f"s_mov_b32 s5, {sel}") + a, b = (fmt[mod].format("v1"), "v2") if side == "src0" else ("v2", fmt[mod].format("v1")) + body += [f"v_cndmask_b32_e64 v3, {a}, {b}, {cond}", f"global_store_b32 v10, v3, s[2:3] offset:{4 * k}"] + base = 4 * len(runs()) + for j, (_, w, insn) in enumerate(CONTROLS): + body += [f"v_mov_b32_e32 v1, 0x{w:08x}", insn, f"global_store_b32 v10, v3, s[2:3] offset:{base + 4 * j}"] + body.append("s_endpgm") + return body + + +def words_per_kernel(): + return len(runs()) + len(CONTROLS) + + +def bit_move(word, mod): + """The sign-bit-move model: `abs` clears bit 31, then `neg` flips it.""" + if "|" in mod: + word &= 0x7FFFFFFF + if mod.startswith("-"): + word ^= 0x80000000 + return word + + +def classify(word, mod, got): + """'bit_move', 'quieted' (a signalling NaN came back quiet), 'flushed' (a denormal came back a zero of its + sign) or 'other', against the sign-bit move of `word`.""" + want = bit_move(word, mod) + if got == want: + return "bit_move" + exp, frac = (want >> 23) & 0xFF, want & 0x7FFFFF + if exp == 0xFF and frac and not frac & 0x400000 and got == want | 0x400000: + return "quieted" + if exp == 0 and frac and got == want & 0x80000000: + return "flushed" + return "other" + + +def control_expected(name, ieee, denorm32): + """The word a control stores when its MODE is in effect.""" + if name == "denorm_add": + return 0x00000000 if denorm32 == 0 else 0x00000001 + if name == "snan_mul": + return 0x7FC00001 if ieee else 0x7F800001 + raise ValueError(f"unknown control {name!r}") + + +def judge(wave, ieee, denorm32, got): + """The report entry of one kernel's stored words.""" + if len(got) != words_per_kernel(): + raise RuntimeError(f"wave{wave} ieee={ieee} denorm32={denorm32}: {len(got)} words, " + f"expected {words_per_kernel()}") + results, counts = [], {c: 0 for c in CLASSES} + for (w, name, mod, side), g in zip(runs(), got): + cls = classify(w, mod, g) + counts[cls] += 1 + results.append({"word": f"0x{w:08x}", "name": name, "mod": mod, "side": side, "got": f"0x{g:08x}", + "class": cls}) + controls = [] + for (name, w, insn), g in zip(CONTROLS, got[len(runs()):]): + want = control_expected(name, ieee, denorm32) + controls.append({"name": name, "insn": insn, "input": f"0x{w:08x}", "got": f"0x{g:08x}", + "expected": f"0x{want:08x}", "ok": g == want}) + return {"wave": wave, "ieee": ieee, "denorm32": denorm32, "counts": counts, + "controls_ok": all(c["ok"] for c in controls), "controls": controls, "results": results} + + +def report_ok(entries): + return all(e["counts"]["bit_move"] == len(e["results"]) and e["controls_ok"] for e in entries) + + +def probe(oracle, asm_mod, waves): + kernels, keys = [], [] + for wave in waves: + lines = kernel_lines(wave) + for ieee, den in MODES: + kernels.append(asm_mod.Kernel(lines, wave=wave, threads=1, words=words_per_kernel(), raw=True, + mode={"ieee": ieee, "denorm32": den})) + keys.append((wave, ieee, den)) + entries = [] + for (wave, ieee, den), got in zip(keys, oracle.run(kernels)): + if isinstance(got, str): + raise RuntimeError(f"wave{wave} ieee={ieee} denorm32={den}: {got}") + entries.append(judge(wave, ieee, den, got)) + return entries + + +def describe(entry): + c = entry["counts"] + line = (f"wave{entry['wave']} ieee={entry['ieee']} denorm32={entry['denorm32']}: " + f"{c['bit_move']}/{len(entry['results'])} sign-bit moves") + others = [f"{c[k]} {k}" for k in CLASSES[1:] if c[k]] + if others: + line += " (" + ", ".join(others) + ")" + ctl = "; ".join(f"{x['name']} {x['got']}" + ("" if x["ok"] else f" (expected {x['expected']})") + for x in entry["controls"]) + line += f"; controls: {ctl}" + ("" if entry["controls_ok"] else " - MODE NOT SHOWN") + return line + + +# ---- self-test and CLI -------------------------------------------------------------------------------------------- + +def self_test(): + assert bit_move(0x7F800001, "-v") == 0xFF800001 + assert bit_move(0xFF800001, "|v|") == 0x7F800001 + assert bit_move(0x80000000, "-|v|") == 0x80000000 + assert bit_move(0x80000000, "-v") == 0x00000000 + assert classify(0x7F800001, "-v", 0xFF800001) == "bit_move" + assert classify(0x7F800001, "-v", 0xFFC00001) == "quieted" + assert classify(0x7FC00000, "v", 0x7FC00000) == "bit_move" + assert classify(0x00000001, "-v", 0x80000000) == "flushed" + assert classify(0x00000001, "|v|", 0x00000000) == "flushed" + assert classify(0x3F800000, "-v", 0x3F800000) == "other" + assert len(runs()) == len(WORDS) * len(MODS) * len(SIDES) == 120 + for wave in (32, 64): + lines = kernel_lines(wave) + assert sum(ln.startswith("global_store_b32") for ln in lines) == words_per_kernel() + assert lines[-1] == "s_endpgm" + assert "v_cndmask_b32_e64 v3, -|v1|, v2, s4" in kernel_lines(32) + assert "v_cndmask_b32_e64 v3, v2, -|v1|, s[4:5]" in kernel_lines(64) + good = [bit_move(w, m) for w, _, m, _ in runs()] + for ieee, den in MODES: + ctl = [control_expected(n, ieee, den) for n, _, _ in CONTROLS] + assert report_ok([judge(32, ieee, den, good + ctl)]) + assert not report_ok([judge(32, ieee, den, good + [ctl[0] ^ 1, ctl[1]])]) + quiet = [g | 0x400000 if (g >> 23) & 0xFF == 0xFF and g & 0x3FFFFF and not g & 0x400000 else g for g in good] + entry = judge(64, 0, 0, quiet + [0, 0x7F800001]) + assert entry["counts"]["quieted"] == 4 * 2 * 3 and not report_ok([entry]) + print("self-test OK") + + +def parse_waves(text): + out = [] + for tok in (t.strip() for t in text.split(",")): + if tok not in ("32", "64"): + raise ValueError(f"invalid wave {tok!r}; expected 32 or 64") + if int(tok) not in out: + out.append(int(tok)) + return out + + +def validate_json_path(path): + """An error string if `path` cannot be a --json output file, or None.""" + if not path or not path.strip(): + return "--json path must not be empty" + if "\x00" in path: + return "--json path contains a NUL byte" + if path.endswith(os.sep) or (os.altsep and path.endswith(os.altsep)) or os.path.isdir(path): + return f"--json path is a directory: {path}" + cur = os.path.dirname(os.path.abspath(path)) + while cur: + if os.path.isdir(cur): + break + if os.path.lexists(cur): + return f"--json parent is not a directory: {cur}" + nxt = os.path.dirname(cur) + if nxt == cur: + break + cur = nxt + return None + + +def write_json_report(path, data): + """Create missing parent directories and write `data` as LF-terminated JSON, or return an error string.""" + parent = os.path.dirname(os.path.abspath(path)) + try: + os.makedirs(parent, exist_ok=True) + with open(path, "w", encoding="utf-8", newline="\n") as f: + json.dump(data, f, indent=2) + f.write("\n") + except OSError as e: + return f"cannot write --json {path}: {e.strerror or e}" + return None + + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("--waves", default="32,64", help="wave sizes to run (default: 32,64)") + ap.add_argument("--json", dest="json_out", help="write the full report to this path") + ap.add_argument("--self-test", action="store_true", help="check the models without a GPU") + args = ap.parse_args(argv) + if args.self_test: + self_test() + return 0 + try: + waves = parse_waves(args.waves) + except ValueError as exc: + print(f"error: {exc}", file=sys.stderr) + return 2 + if args.json_out is not None: + err = validate_json_path(args.json_out) + if err: + print(f"error: {err}", file=sys.stderr) + return 2 + from hw_oracle import asm, runner + try: + oracle = runner.open_oracle() + except runner.Unavailable as exc: + print(f"SKIP: {exc}", file=sys.stderr) + return 77 + try: + try: + fam = asm.family(oracle.arch) + except ValueError: + fam = None + if fam not in FAMILIES or asm.mode_skip_reason({"ieee": 1}, oracle.arch): + print(f"SKIP: {oracle.arch} cannot set the IEEE mode these kernels need (gfx10 / gfx11 before " + "gfx1170 only)", file=sys.stderr) + return 77 + try: + entries = probe(oracle, asm, waves) + except RuntimeError as exc: + print(f"error: {exc}", file=sys.stderr) + return 2 + finally: + close = getattr(oracle, "close", None) + if close: + close() + print(f"device: {oracle.arch}") + for entry in entries: + print(describe(entry)) + ok = report_ok(entries) + print("result: " + ("every source modifier is a sign-bit move, every MODE shown" if ok + else "NOT every result is a sign-bit move with its MODE shown; see above")) + if args.json_out is not None: + err = write_json_report(args.json_out, {"arch": oracle.arch, "ok": ok, "kernels": entries}) + if err: + print(f"error: {err}", file=sys.stderr) + return 1 + return 0 if ok else 1 + + +if __name__ == "__main__": + if hasattr(sys.stdout, "reconfigure"): + sys.stdout.reconfigure(errors="replace") + raise SystemExit(main())