upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorVonsek <45567075+Vonsek@users.noreply.github.com>2026-11-22 20:15:34 +0100
committerVonsek <45567075+Vonsek@users.noreply.github.com>2026-11-22 20:15:34 +0100
commit4c414d121663c06ab2cbfb04596cc2a39457be77 (patch)
treee72d50d0ee8de6ccb4aa3a8d4650013bd69a3fbc
parent162821017ea3c286c8bec860f3ff94f037912061 (diff)
tools: ps_oracle.py runs hand-written RDNA2 pixel-shader ISA on AMD GPUs
hw_oracle launches compute kernels only. vk_harness can now write a pipeline's VK_KHR_pipeline_binary data and build a pipeline from it (VKH_BINARY_OUT / VKH_BINARY_IN). ps_oracle.py puts assembled ISA in place of _amdgpu_ps_main in the driver's PAL ELF, raises the pixel stage's register counts in the msgpack metadata, optionally changes other metadata entries, and draws with it, reading every pixel's mrt0 words back. Checked on gfx1036 (driver 26.10.1): v_interp of a varying and the parameter words P0 / P10 come back as expected. Tests in tests/test_ps_oracle.py, docs in docs/shader_validation.md. AI-assisted.
-rw-r--r--docs/shader_validation.md38
-rw-r--r--runtime/test/vk_harness.cpp96
-rw-r--r--tests/test_ps_oracle.py184
-rw-r--r--tools/ps_oracle.py670
4 files changed, 988 insertions, 0 deletions
diff --git a/docs/shader_validation.md b/docs/shader_validation.md
index bbc748aa9..46bf9863b 100644
--- a/docs/shader_validation.md
+++ b/docs/shader_validation.md
@@ -1418,6 +1418,44 @@ Hardware validation was executed via `tools/hw_oracle` and `tools/salu_diff.py`
1418- **24-bit products and 64-bit shifts (`v_mul_hi_*24`, `v_lshrrev_b64`, `v_ashrrev_i64`)**: 1418- **24-bit products and 64-bit shifts (`v_mul_hi_*24`, `v_lshrrev_b64`, `v_ashrrev_i64`)**:
1419 - Verified across signed/unsigned products, edge signs, and 0..63 shift counts: **0 mismatches**. 1419 - Verified across signed/unsigned products, edge signs, and 0..63 shift counts: **0 mismatches**.
1420 1420
1421### Pixel-shader ISA on the hardware (`tools/ps_oracle.py`, EGEN-TOOL-PS-ORACLE)
1422
1423`tools/hw_oracle` only launches compute kernels, so what only a pixel shader has (`v_interp_*` and the parameter
1424words the SPI writes into LDS, the barycentric VGPRs, exports and their formats, helper lanes) could not be
1425measured there. `tools/ps_oracle.py` runs hand-written RDNA2 pixel-shader ISA in a real draw on an AMD GPU, through
1426Vulkan's `VK_KHR_pipeline_binary`:
1427
14281. `vk_harness` builds a pipeline from a template vertex + pixel shader and writes its binary (`VKH_BINARY_OUT`).
1429 On the AMD Windows driver that is one PAL ELF: `.text` with `_amdgpu_gs_main` (the vertex stage) and
1430 `_amdgpu_ps_main`, and a `.note` with the PAL metadata in msgpack, from which the driver programs the register
1431 counts and the SPI setup (`spi_ps_input_ena/addr`, `spi_ps_input_cntl` per parameter, `spi_shader_col_format`).
14322. The code under test is assembled with AMD clang (`LEONIDA_AMD_CLANG`, as for hw_oracle) and replaces
1433 `_amdgpu_ps_main`; `.text` grows if needed and the pixel stage's VGPR/SGPR counts are raised to the registers
1434 the code names. `--set PATH=JSON` changes a metadata entry as well, e.g.
1435 `.graphics_registers/.spi_ps_input_cntl/0/.fp16_interp_mode=true`.
14363. `vk_harness` builds the pipeline from the patched binary (`VKH_BINARY_IN`), draws one full-screen triangle into
1437 an RGBA32F target and reads every pixel's four mrt0 dwords back bit for bit.
1438
1439The template sets what the code finds when it starts, so `--show-template` prints the template's own ISA and SPI
1440metadata to copy the conventions from. With the built-in `interp2` template on gfx1036 the pixel stage is wave64,
1441the perspective I/J barycentrics are in v0/v1, M0 comes from s2 (`s_mov_b32 m0, s2`), and parameters 0 and 1 are
1442the vertex shader's locations 0 = (u, v, 0, 1) and 1 = (u, v, 0, 0), u and v going 0..2 across the screen.
1443
1444```powershell
1445$env:LEONIDA_VK_DEVICE = "radeon"
1446python -I tools/ps_oracle.py --build <runtime build> --template interp2 --show-template
1447python -I tools/ps_oracle.py --build <runtime build> --template interp2 --asm body.s --size 4 1 [--json out.json]
1448```
1449
1450Checked on an AMD Radeon iGPU (gfx1036, Windows driver 26.10.1): the driver accepts a patched binary (there is no
1451check over the code), the patched code runs as the pixel shader, and `v_interp_p1/p2_f32` of `attr0.x` at the four
1452pixel centres of a 4 x 1 target gives u = 0.125, 0.375, 0.625, 0.875, with `v_interp_mov_f32` reading the
1453parameter words P0 = 0 and P10 = 2.0 (`tests/test_ps_oracle.py`, which runs it on hardware when
1454`LEONIDA_PS_ORACLE_BUILD` names a runtime build). On other drivers the binary is not a single PAL ELF (the NVIDIA
1455driver returns two blobs) and the tool exits 77. Limits: one draw of one triangle, mrt0 as RGBA32F only; the vertex
1456stage is the template's, compiled by the driver; the SPI behaviour comes from the driver's metadata, so a `--set`
1457the hardware does not support is not refused here.
1458
1421 1459
1422## Coverage plan and cost 1460## Coverage plan and cost
1423 1461
diff --git a/runtime/test/vk_harness.cpp b/runtime/test/vk_harness.cpp
index fe9ae194a..c296c9df4 100644
--- a/runtime/test/vk_harness.cpp
+++ b/runtime/test/vk_harness.cpp
@@ -15,6 +15,9 @@
15// draws an indexed mesh instead of the 3-vertex triangle. The file is u32 15// draws an indexed mesh instead of the 3-vertex triangle. The file is u32
16// vertex_count, u32 index_count, vertex_count*stride bytes, index_count u32 16// vertex_count, u32 index_count, vertex_count*stride bytes, index_count u32
17// indices; the layout lists location:float-components, one item per attribute. 17// indices; the layout lists location:float-components, one item per attribute.
18// VKH_BINARY_OUT=<file> writes the pipeline's VK_KHR_pipeline_binary data after building it
19// VKH_BINARY_IN=<file> builds the pipeline from such a file instead (tools/ps_oracle.py patches the pixel
20// shader in it); both exit 77 without VK_KHR_pipeline_binary
18// VKH_SUBGROUP_SIZE=32|64 requires that subgroup size of the fragment shader (or of the compute or geometry 21// VKH_SUBGROUP_SIZE=32|64 requires that subgroup size of the fragment shader (or of the compute or geometry
19// stage under test); stderr says "fragment subgroup size: N" when it took effect and 22// stage under test); stderr says "fragment subgroup size: N" when it took effect and
20// "... not available" when the device cannot require it (exit code stays 0). 23// "... not available" when the device cannot require it (exit code stays 0).
@@ -30,6 +33,7 @@
30#include <cstdlib> 33#include <cstdlib>
31#include <cstring> 34#include <cstring>
32#include <fstream> 35#include <fstream>
36#include <iterator>
33#include <utility> 37#include <utility>
34#include <vector> 38#include <vector>
35 39
@@ -349,6 +353,29 @@ int main(int argc, char** argv) {
349 f12.pNext = chain; 353 f12.pNext = chain;
350 chain = &f12; 354 chain = &f12;
351 } 355 }
356 // VKH_BINARY_OUT=<file> / VKH_BINARY_IN=<file>: VK_KHR_pipeline_binary. OUT writes the pipeline's binaries after
357 // it is built; IN builds the pipeline from such a file instead of compiling the shaders (tools/ps_oracle.py
358 // patches the pixel shader's code in it). File: u32 count, then per binary u32 key size, 32 key bytes, u64 data
359 // size, the data.
360 const char* bin_out = std::getenv("VKH_BINARY_OUT");
361 const char* bin_in = std::getenv("VKH_BINARY_IN");
362 VkPhysicalDevicePipelineBinaryFeaturesKHR pbf{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_BINARY_FEATURES_KHR};
363 VkPhysicalDeviceMaintenance5FeaturesKHR m5{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_5_FEATURES_KHR};
364 if (bin_out || bin_in) {
365 VkPhysicalDeviceFeatures2 q{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2};
366 VkPhysicalDevicePipelineBinaryFeaturesKHR pbq{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_BINARY_FEATURES_KHR};
367 q.pNext = &pbq;
368 vkGetPhysicalDeviceFeatures2(pd, &q);
369 if (!has(VK_KHR_PIPELINE_BINARY_EXTENSION_NAME) || !has(VK_KHR_MAINTENANCE_5_EXTENSION_NAME) ||
370 !pbq.pipelineBinaries) {
371 std::fprintf(stderr, "unsupported: no VK_KHR_pipeline_binary\n");
372 return 77;
373 }
374 enable.push_back(VK_KHR_PIPELINE_BINARY_EXTENSION_NAME);
375 enable.push_back(VK_KHR_MAINTENANCE_5_EXTENSION_NAME);
376 pbf.pipelineBinaries = VK_TRUE; pbf.pNext = chain; chain = &pbf;
377 m5.maintenance5 = VK_TRUE; m5.pNext = chain; chain = &m5;
378 }
352 for (auto e : enable) std::fprintf(stderr, "enabled %s\n", e); 379 for (auto e : enable) std::fprintf(stderr, "enabled %s\n", e);
353 VkDeviceCreateInfo dci{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO}; 380 VkDeviceCreateInfo dci{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO};
354 dci.queueCreateInfoCount = 1; dci.pQueueCreateInfos = &qci; 381 dci.queueCreateInfoCount = 1; dci.pQueueCreateInfos = &qci;
@@ -554,7 +581,76 @@ int main(int argc, char** argv) {
554 gpi.pDepthStencilState = &ds_state; 581 gpi.pDepthStencilState = &ds_state;
555 } 582 }
556 gpi.layout = pl; gpi.renderPass = rp; 583 gpi.layout = pl; gpi.renderPass = rp;
584 VkPipelineCreateFlags2CreateInfoKHR capture{VK_STRUCTURE_TYPE_PIPELINE_CREATE_FLAGS_2_CREATE_INFO_KHR};
585 std::vector<VkPipelineBinaryKHR> in_bins;
586 VkPipelineBinaryInfoKHR bin_info{VK_STRUCTURE_TYPE_PIPELINE_BINARY_INFO_KHR};
587 if (bin_out) {
588 capture.flags = VK_PIPELINE_CREATE_2_CAPTURE_DATA_BIT_KHR;
589 gpi.pNext = &capture;
590 }
591 if (bin_in) {
592 auto vkCreatePipelineBinariesKHR = reinterpret_cast<PFN_vkCreatePipelineBinariesKHR>(
593 vkGetDeviceProcAddr(dev, "vkCreatePipelineBinariesKHR"));
594 std::ifstream f(bin_in, std::ios::binary);
595 std::vector<char> all((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
596 size_t at = 0;
597 auto take = [&](void* p, size_t n) {
598 if (at + n > all.size()) { std::fprintf(stderr, "%s: truncated\n", bin_in); std::exit(2); }
599 std::memcpy(p, all.data() + at, n); at += n;
600 };
601 uint32_t count = 0; take(&count, 4);
602 std::vector<VkPipelineBinaryKeyKHR> keys(count, {VK_STRUCTURE_TYPE_PIPELINE_BINARY_KEY_KHR});
603 std::vector<VkPipelineBinaryDataKHR> datas(count);
604 std::vector<std::vector<char>> blobs(count);
605 for (uint32_t i = 0; i < count; i++) {
606 take(&keys[i].keySize, 4); take(keys[i].key, VK_MAX_PIPELINE_BINARY_KEY_SIZE_KHR);
607 uint64_t n = 0; take(&n, 8);
608 blobs[i].resize(size_t(n)); take(blobs[i].data(), size_t(n));
609 datas[i].dataSize = size_t(n); datas[i].pData = blobs[i].data();
610 }
611 VkPipelineBinaryKeysAndDataKHR kd{count, keys.data(), datas.data()};
612 VkPipelineBinaryCreateInfoKHR bci{VK_STRUCTURE_TYPE_PIPELINE_BINARY_CREATE_INFO_KHR};
613 bci.pKeysAndDataInfo = &kd;
614 in_bins.resize(count);
615 VkPipelineBinaryHandlesInfoKHR hi{VK_STRUCTURE_TYPE_PIPELINE_BINARY_HANDLES_INFO_KHR};
616 hi.pipelineBinaryCount = count; hi.pPipelineBinaries = in_bins.data();
617 CHECK(vkCreatePipelineBinariesKHR(dev, &bci, nullptr, &hi));
618 bin_info.binaryCount = count; bin_info.pPipelineBinaries = in_bins.data();
619 gpi.pNext = &bin_info;
620 std::fprintf(stderr, "pipeline from %u binaries in %s\n", count, bin_in);
621 }
557 VkPipeline pipe; CHECK(vkCreateGraphicsPipelines(dev, VK_NULL_HANDLE, 1, &gpi, nullptr, &pipe)); 622 VkPipeline pipe; CHECK(vkCreateGraphicsPipelines(dev, VK_NULL_HANDLE, 1, &gpi, nullptr, &pipe));
623 if (bin_out) {
624 auto vkCreatePipelineBinariesKHR = reinterpret_cast<PFN_vkCreatePipelineBinariesKHR>(
625 vkGetDeviceProcAddr(dev, "vkCreatePipelineBinariesKHR"));
626 auto vkGetPipelineBinaryDataKHR = reinterpret_cast<PFN_vkGetPipelineBinaryDataKHR>(
627 vkGetDeviceProcAddr(dev, "vkGetPipelineBinaryDataKHR"));
628 VkPipelineBinaryCreateInfoKHR bci{VK_STRUCTURE_TYPE_PIPELINE_BINARY_CREATE_INFO_KHR};
629 bci.pipeline = pipe;
630 VkPipelineBinaryHandlesInfoKHR hi{VK_STRUCTURE_TYPE_PIPELINE_BINARY_HANDLES_INFO_KHR};
631 CHECK(vkCreatePipelineBinariesKHR(dev, &bci, nullptr, &hi));
632 std::vector<VkPipelineBinaryKHR> bins(hi.pipelineBinaryCount);
633 hi.pPipelineBinaries = bins.data();
634 CHECK(vkCreatePipelineBinariesKHR(dev, &bci, nullptr, &hi));
635 std::ofstream f(bin_out, std::ios::binary);
636 uint32_t count = uint32_t(bins.size());
637 f.write(reinterpret_cast<const char*>(&count), 4);
638 for (auto b : bins) {
639 VkPipelineBinaryDataInfoKHR di{VK_STRUCTURE_TYPE_PIPELINE_BINARY_DATA_INFO_KHR};
640 di.pipelineBinary = b;
641 VkPipelineBinaryKeyKHR key{VK_STRUCTURE_TYPE_PIPELINE_BINARY_KEY_KHR};
642 size_t n = 0;
643 CHECK(vkGetPipelineBinaryDataKHR(dev, &di, &key, &n, nullptr));
644 std::vector<char> data(n);
645 CHECK(vkGetPipelineBinaryDataKHR(dev, &di, &key, &n, data.data()));
646 uint64_t n64 = n;
647 f.write(reinterpret_cast<const char*>(&key.keySize), 4);
648 f.write(reinterpret_cast<const char*>(key.key), VK_MAX_PIPELINE_BINARY_KEY_SIZE_KHR);
649 f.write(reinterpret_cast<const char*>(&n64), 8);
650 f.write(data.data(), std::streamsize(n));
651 }
652 std::fprintf(stderr, "wrote %u pipeline binaries to %s\n", count, bin_out);
653 }
558 VkPipeline cpipe = VK_NULL_HANDLE; 654 VkPipeline cpipe = VK_NULL_HANDLE;
559 if (mesh_compute) { 655 if (mesh_compute) {
560 VkComputePipelineCreateInfo cpi{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; 656 VkComputePipelineCreateInfo cpi{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO};
diff --git a/tests/test_ps_oracle.py b/tests/test_ps_oracle.py
new file mode 100644
index 000000000..cbb4aa9b0
--- /dev/null
+++ b/tests/test_ps_oracle.py
@@ -0,0 +1,184 @@
1"""tools/ps_oracle.py: the msgpack subset, the PAL ELF rewrite that puts new pixel-shader code in a pipeline binary,
2the binary file format, and (with LEONIDA_PS_ORACLE_BUILD set to a runtime build and an AMD GPU selected) a real
3draw with patched code. Standard library only."""
4import os
5import struct
6import sys
7import tempfile
8import unittest
9
10ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
11sys.path.insert(0, os.path.join(ROOT, "tools"))
12import ps_oracle as P # noqa: E402
13
14S_ENDPGM = struct.pack("<I", 0xBF810000)
15S_VERSION_W64 = struct.pack("<I", 0xB0802004)
16
17
18def _meta(vgprs=4, sgprs=6):
19 return {"amdpal.version": [3, 6], "amdpal.pipelines": [{
20 ".api": "Vulkan",
21 ".hardware_stages": {".gs": {".vgpr_count": 46, ".sgpr_count": 20},
22 ".ps": {".vgpr_count": vgprs, ".sgpr_count": sgprs, ".entry_point_symbol": P.PS_SYMBOL,
23 ".checksum_value": 780697862}},
24 ".graphics_registers": {".spi_ps_input_cntl": [{".offset": 0, ".fp16_interp_mode": False}],
25 ".spi_ps_in_control": {".num_interps": 1}},
26 ".scale": P.F32(0.5),
27 }]}
28
29
30def _elf(gs_code, ps_code, ps_at, meta):
31 """A small ELF laid out like the AMD driver's pipeline binary: .shstrtab, .text (gs then ps), .comment, .strtab,
32 .symtab and the AMDGPU metadata note, no program headers."""
33 names = [b"", b".shstrtab", b".text", b".comment", b".strtab", b".symtab", b".note"]
34 shstr = b"\0".join(names) + b"\0"
35 off = {n: shstr.index(n + b"\0") if n else 0 for n in names}
36 text = gs_code + b"\0" * (ps_at - len(gs_code)) + ps_code
37 strtab = b"\0_amdgpu_gs_main\0" + P.PS_SYMBOL.encode() + b"\0"
38 sym = b"\0" * 24
39 sym += struct.pack("<IBBHQQ", 1, 0x12, 0, 2, 0, len(gs_code))
40 sym += struct.pack("<IBBHQQ", strtab.index(P.PS_SYMBOL.encode()), 0x12, 0, 2, ps_at, len(ps_code))
41 desc = P.mp_dump(meta)
42 note = struct.pack("<III", 7, len(desc), 32) + b"AMDGPU\0\0" + desc
43 note += b"\0" * (-len(note) % 4)
44 secs = [(".shstrtab", 3, shstr, 0, 0), (".text", 1, text, 0, 0), (".comment", 1, b"test\0", 0, 0),
45 (".strtab", 3, strtab, 0, 0), (".symtab", 2, sym, 4, 24), (".note", 7, note, 0, 0)]
46 body, hdrs, at = bytearray(), [(0,) * 10], 64
47 for name, typ, data, link, ent in secs:
48 hdrs.append((off[name.encode()], typ, 6 if name == ".text" else 0, 0, at, len(data), link, 0,
49 256 if name == ".text" else 0, ent))
50 body += data
51 at += len(data)
52 while (64 + len(body)) % 8:
53 body += b"\0"
54 head = bytearray(64)
55 head[:16] = b"\x7fELF\x02\x01\x01\x41" + bytes(8)
56 struct.pack_into("<HHIQQQIHHHHHH", head, 16, 1, 0xE0, 1, 0, 0, 64 + len(body), 0x945, 64, 0, 0, 64,
57 len(hdrs), 1)
58 return bytes(head) + bytes(body) + b"".join(struct.pack(P._SH, *h) for h in hdrs)
59
60
61class Msgpack(unittest.TestCase):
62 def test_round_trip(self):
63 values = [0, 127, 128, 255, 256, 65536, 1 << 40, -1, -32, -33, -200, -40000, -(1 << 40), True, False, None,
64 "", "x" * 31, "y" * 32, "z" * 300, b"\x01\x02", [], list(range(20)), {"a": 1, "b": [1, {"c": None}]},
65 {str(i): i for i in range(20)}, 1.5, P.F32(0.25)]
66 for v in values:
67 with self.subTest(v=v if not isinstance(v, str) else v[:5]):
68 got, end = P.mp_load(P.mp_dump(v))
69 self.assertEqual(got, v)
70 self.assertEqual(end, len(P.mp_dump(v)))
71 self.assertEqual(type(got) is P.F32, type(v) is P.F32)
72
73 def test_minimal_encodings(self):
74 self.assertEqual(P.mp_dump(5), b"\x05")
75 self.assertEqual(P.mp_dump(200), b"\xcc\xc8")
76 self.assertEqual(P.mp_dump(-5), b"\xfb")
77 self.assertEqual(P.mp_dump(P.F32(1.0)), b"\xca\x3f\x80\x00\x00")
78 self.assertEqual(P.mp_dump({"a": 1}), b"\x81\xa1a\x01")
79 with self.assertRaises(ValueError):
80 P.mp_load(b"\xc1")
81
82
83class PatchPixelShader(unittest.TestCase):
84 def setUp(self):
85 self.gs = S_VERSION_W64 + S_ENDPGM
86 self.ps = S_VERSION_W64 + struct.pack("<II", 0x7E0002FF, 0x3F800000) + S_ENDPGM
87 self.elf = _elf(self.gs, self.ps, 0x100, _meta())
88
89 def test_the_test_elf_reads_back(self):
90 e = P.Elf(self.elf)
91 self.assertEqual([s[0] for s in e.symbols()], ["", "_amdgpu_gs_main", P.PS_SYMBOL])
92 self.assertEqual(P.ps_stage(e.metadata())[".vgpr_count"], 4)
93 self.assertEqual(P.ps_code(self.elf), (0x100, self.ps))
94 self.assertTrue(P.is_wave64(self.elf))
95
96 def test_longer_code_grows_text_and_keeps_everything_else(self):
97 code = S_VERSION_W64 + struct.pack("<II", 0x7E0002FF, 0x12345678) * 50 + S_ENDPGM
98 out = P.patch_ps(self.elf, code, ["v_mov_b32 v40, 0", "s_mov_b32 s[20:21], 0"],
99 [(".graphics_registers/.spi_ps_input_cntl/0/.fp16_interp_mode", True)])
100 e = P.Elf(out)
101 text = bytes(e.data[e.index(".text")])
102 self.assertEqual(text[:len(self.gs)], self.gs) # the vertex stage is untouched
103 self.assertEqual(text[0x100:0x100 + len(code)], code)
104 pad = text[0x100 + len(code):]
105 self.assertGreaterEqual(len(pad), 256) # s_code_end past the end, as the driver
106 self.assertEqual(pad, P.S_CODE_END * (len(pad) // 4))
107 self.assertEqual((0x100 + len(code) + len(pad)) % 64, 0)
108 sym = {s[0]: s for s in e.symbols()}
109 self.assertEqual(sym[P.PS_SYMBOL][1:3], (0x100, len(code) + (len(pad) - 256)))
110 meta = e.metadata()
111 ps = P.ps_stage(meta)
112 self.assertEqual((ps[".vgpr_count"], ps[".sgpr_count"]), (41, 22)) # raised to the registers named
113 self.assertEqual(ps[".checksum_value"], 780697862)
114 regs = meta["amdpal.pipelines"][0][".graphics_registers"]
115 self.assertIs(regs[".spi_ps_input_cntl"][0][".fp16_interp_mode"], True)
116 self.assertIs(type(meta["amdpal.pipelines"][0][".scale"]), P.F32)
117 self.assertEqual(bytes(e.data[e.index(".comment")]), b"test\0")
118 self.assertEqual(P.Elf(e.to_bytes()).to_bytes(), out) # stable when written again
119
120 def test_counts_are_never_lowered_and_an_untouched_note_is_kept(self):
121 out = P.patch_ps(_elf(self.gs, self.ps, 0x100, _meta(vgprs=64, sgprs=40)), self.ps, ["v_mov_b32 v1, s2"])
122 e = P.Elf(out)
123 self.assertEqual(P.ps_stage(e.metadata())[".vgpr_count"], 64)
124 self.assertEqual(bytes(e.data[e.index(".note")]),
125 bytes(P.Elf(_elf(self.gs, self.ps, 0x100, _meta(64, 40))).data[e.index(".note")]))
126
127 def test_refusals(self):
128 e = P.Elf(self.elf) # the vertex stage moved after the pixel stage
129 struct.pack_into("<Q", e.data[e.index(".symtab")], 24 + 8, 0x200)
130 with self.assertRaises(ValueError):
131 P.patch_ps(e.to_bytes(), self.ps)
132 with self.assertRaises(ValueError):
133 P.patch_ps(self.elf, self.ps, [], [(".graphics_registers/.no_such_register", 1)])
134 with self.assertRaises(P.Unavailable):
135 P.Elf(b"MZ" + bytes(100))
136
137 def test_registers_named(self):
138 self.assertEqual(P.regs_used(["v_interp_p1_f32_e32 v4, v0, attr0.z", "s_mov_b32 m0, s2",
139 "v_mad_u64_u32 v[8:9], s[10:11], v1, v1, v[2:3] ; v200"]), (10, 12))
140
141
142class BinaryFile(unittest.TestCase):
143 def test_round_trip(self):
144 bins = [(16, bytes(range(32)), b"\x7fELF" + bytes(40)), (32, b"\xff" * 32, b"")]
145 with tempfile.TemporaryDirectory() as d:
146 p = os.path.join(d, "b.bin")
147 P.write_binaries(p, bins)
148 self.assertEqual(P.read_binaries(p), bins)
149
150
151class Cli(unittest.TestCase):
152 def test_nothing_to_do_is_a_usage_error(self):
153 with self.assertRaises(SystemExit) as cm:
154 P.main(["--build", "."])
155 self.assertEqual(cm.exception.code, 2)
156
157 def test_no_harness_is_unavailable(self):
158 with tempfile.TemporaryDirectory() as d:
159 self.assertEqual(P.main(["--build", d, "--show-template"]), 77)
160
161
162@unittest.skipUnless(os.environ.get("LEONIDA_PS_ORACLE_BUILD"), "set LEONIDA_PS_ORACLE_BUILD to a runtime build "
163 "and select an AMD GPU (LEONIDA_VK_DEVICE) to run the pixel shader on hardware")
164class OnHardware(unittest.TestCase):
165 def test_patched_code_runs_as_the_pixel_shader(self):
166 # interp2: location 0 is (u, v, 0, 1), u = 0 at vertex 0 and 2 at vertex 1, so on a 4 x 1 target pixel x has
167 # u = (x + 0.5) / 4. The parameter words in LDS are P0 = 0 (vertex 0) and P10 = 2.0 (vertex 1 - vertex 0).
168 try:
169 o = P.Oracle(os.environ["LEONIDA_PS_ORACLE_BUILD"], template="interp2", size=(4, 1))
170 except P.Unavailable as e:
171 self.skipTest(str(e))
172 try:
173 px = o.run(["s_mov_b32 m0, s2", "v_interp_p1_f32_e32 v2, v0, attr0.x", "v_interp_p2_f32_e32 v2, v1, attr0.x",
174 "v_interp_mov_f32_e32 v3, p0, attr0.x", "v_interp_mov_f32_e32 v4, p10, attr0.x",
175 "v_mov_b32_e32 v40, 0x12345678", "v_mov_b32_e32 v5, v40",
176 "exp mrt0, v2, v3, v4, v5 done vm", "s_endpgm"])
177 finally:
178 o.close()
179 want_u = [0x3E000000, 0x3EC00000, 0x3F200000, 0x3F600000] # 0.125, 0.375, 0.625, 0.875
180 self.assertEqual(px, [[u, 0, 0x40000000, 0x12345678] for u in want_u])
181
182
183if __name__ == "__main__":
184 unittest.main()
diff --git a/tools/ps_oracle.py b/tools/ps_oracle.py
new file mode 100644
index 000000000..56138e716
--- /dev/null
+++ b/tools/ps_oracle.py
@@ -0,0 +1,670 @@
1r"""Run hand-written RDNA2 pixel-shader ISA on an AMD GPU: a hardware oracle for what only a pixel shader can do.
2
3tools/hw_oracle launches compute kernels; v_interp_*, the parameter data the SPI writes into LDS, exports and helper
4lanes need a real draw. This tool gets one through Vulkan's VK_KHR_pipeline_binary (the AMD Windows driver exposes
5it, with uncompressed data):
6
7 1. vk_harness builds a pipeline from a template vertex + pixel shader (SPIR-V) and writes its binary
8 (VKH_BINARY_OUT). On AMD that binary is one PAL ELF: `.text` holds `_amdgpu_gs_main` (the vertex stage) and
9 `_amdgpu_ps_main`, the `.note` holds the PAL metadata (msgpack): register counts and the SPI setup
10 (SPI_PS_INPUT_ENA/ADDR, the parameter layout, the export format), which the driver programs from the metadata.
11 2. The ISA under test is assembled with AMD clang (gfx1036 or the --mcpu given) and replaces `_amdgpu_ps_main`;
12 `.text` grows when it is longer, and the pixel stage's VGPR/SGPR counts in the metadata are raised to cover the
13 registers it names.
14 3. vk_harness builds the pipeline from the patched binary (VKH_BINARY_IN), draws one full-screen triangle into an
15 RGBA32F target and reads it back, so every pixel's mrt0 export comes back as four raw dwords.
16
17The template decides what the hardware sets up before the code runs: which barycentrics are in VGPRs, which user
18SGPRs hold what (the PS sets M0 from one of them for v_interp), how many parameters the SPI writes into LDS and in
19what format, and the export format of mrt0 (32_ABGR for the harness' RGBA32F target). --show-template prints the
20template's own ISA and that part of its metadata, so the code under test can follow the same conventions.
21Templates: `const` (no inputs), `interp2` (two smooth vec4 varyings: location 0 = (u, v, 0, 1) and location 1 =
22(u, v, 0, 0) with u, v = 0..2 across the screen, as scripts/run_gpu_tests.py's vs_tri), or --vs/--ps files
23(.spv, or .spvasm assembled with spirv-as).
24
25Checked on an AMD Radeon iGPU (gfx1036, Windows driver 26.10.1): the driver accepts a patched binary and the patched
26code runs as the pixel shader (no checksum over the code). The pixel stage there is compiled as wave64.
27
28Usage:
29 python -I tools/ps_oracle.py --build <runtime build> --template interp2 --show-template
30 python -I tools/ps_oracle.py --build <runtime build> --template interp2 --asm body.s [--size 8 8] [--json out.json]
31
32Select the AMD GPU with LEONIDA_VK_DEVICE (e.g. radeon). Standard library only; needs vk_harness from the runtime
33build, AMD clang (LEONIDA_AMD_CLANG, as tools/hw_oracle), llvm-objdump next to it for --show-template, and
34spirv-as on PATH for the templates. Exit codes: 0 ran, 1 the GPU run failed, 2 usage or a bad input, 77 the
35device or a tool is missing (no VK_KHR_pipeline_binary, not an AMD PAL binary, no clang).
36"""
37import argparse
38import json
39import os
40import re
41import struct
42import subprocess
43import sys
44import tempfile
45
46HERE = os.path.dirname(os.path.abspath(__file__))
47sys.path.insert(0, HERE)
48
49PS_SYMBOL = "_amdgpu_ps_main"
50S_CODE_END = struct.pack("<I", 0xBF9F0000)
51W64_BIT = 0x2000 # s_version's UC_VERSION_W64_BIT
52
53
54class Unavailable(Exception):
55 """A tool or a device feature is missing: exit 77."""
56
57
58# ---- msgpack, the subset PAL metadata uses ----
59
60class F32(float):
61 """A float that was (and is written back as) msgpack float32."""
62
63
64def mp_load(b, i=0):
65 """(value, next index). Maps become dicts (key order kept), floats keep their width (F32 / float)."""
66 t = b[i]
67 if t <= 0x7F:
68 return t, i + 1
69 if t >= 0xE0:
70 return t - 0x100, i + 1
71 if 0x80 <= t <= 0x8F or t in (0xDE, 0xDF):
72 n, i = (t & 0x0F, i + 1) if t <= 0x8F else (struct.unpack_from(">H" if t == 0xDE else ">I", b, i + 1)[0],
73 i + (3 if t == 0xDE else 5))
74 d = {}
75 for _ in range(n):
76 k, i = mp_load(b, i)
77 v, i = mp_load(b, i)
78 d[k] = v
79 return d, i
80 if 0x90 <= t <= 0x9F or t in (0xDC, 0xDD):
81 n, i = (t & 0x0F, i + 1) if t <= 0x9F else (struct.unpack_from(">H" if t == 0xDC else ">I", b, i + 1)[0],
82 i + (3 if t == 0xDC else 5))
83 out = []
84 for _ in range(n):
85 v, i = mp_load(b, i)
86 out.append(v)
87 return out, i
88 if 0xA0 <= t <= 0xBF or t in (0xD9, 0xDA, 0xDB):
89 if t <= 0xBF:
90 n, i = t & 0x1F, i + 1
91 else:
92 w = {0xD9: 1, 0xDA: 2, 0xDB: 4}[t]
93 n, i = int.from_bytes(b[i + 1:i + 1 + w], "big"), i + 1 + w
94 return b[i:i + n].decode("utf-8"), i + n
95 if t in (0xC4, 0xC5, 0xC6):
96 w = {0xC4: 1, 0xC5: 2, 0xC6: 4}[t]
97 n = int.from_bytes(b[i + 1:i + 1 + w], "big")
98 return bytes(b[i + 1 + w:i + 1 + w + n]), i + 1 + w + n
99 if t == 0xC0:
100 return None, i + 1
101 if t in (0xC2, 0xC3):
102 return t == 0xC3, i + 1
103 if t == 0xCA:
104 return F32(struct.unpack_from(">f", b, i + 1)[0]), i + 5
105 if t == 0xCB:
106 return struct.unpack_from(">d", b, i + 1)[0], i + 9
107 ints = {0xCC: ">B", 0xCD: ">H", 0xCE: ">I", 0xCF: ">Q", 0xD0: ">b", 0xD1: ">h", 0xD2: ">i", 0xD3: ">q"}
108 if t in ints:
109 return struct.unpack_from(ints[t], b, i + 1)[0], i + 1 + struct.calcsize(ints[t])
110 raise ValueError(f"msgpack type 0x{t:02x} at {i} is not supported")
111
112
113def _mp_len(n, small, small_max, wide):
114 if n <= small_max:
115 return bytes([small | n])
116 for code, fmt, top in wide:
117 if n < top:
118 return bytes([code]) + struct.pack(fmt, n)
119 raise ValueError("too long")
120
121
122def mp_dump(v):
123 if v is None:
124 return b"\xc0"
125 if v is True or v is False:
126 return b"\xc3" if v else b"\xc2"
127 if isinstance(v, int):
128 if 0 <= v <= 0x7F:
129 return bytes([v])
130 if -32 <= v < 0:
131 return bytes([v + 0x100])
132 for code, fmt, lo, hi in ((0xCC, ">B", 0, 1 << 8), (0xCD, ">H", 0, 1 << 16), (0xCE, ">I", 0, 1 << 32),
133 (0xCF, ">Q", 0, 1 << 64), (0xD0, ">b", -(1 << 7), 0), (0xD1, ">h", -(1 << 15), 0),
134 (0xD2, ">i", -(1 << 31), 0), (0xD3, ">q", -(1 << 63), 0)):
135 if lo <= v < hi:
136 return bytes([code]) + struct.pack(fmt, v)
137 raise ValueError(f"integer {v} out of range")
138 if isinstance(v, F32):
139 return b"\xca" + struct.pack(">f", v)
140 if isinstance(v, float):
141 return b"\xcb" + struct.pack(">d", v)
142 if isinstance(v, str):
143 s = v.encode("utf-8")
144 if len(s) <= 31:
145 return bytes([0xA0 | len(s)]) + s
146 return _mp_len(len(s), 0, -1, ((0xD9, ">B", 1 << 8), (0xDA, ">H", 1 << 16), (0xDB, ">I", 1 << 32))) + s
147 if isinstance(v, (bytes, bytearray)):
148 return _mp_len(len(v), 0, -1, ((0xC4, ">B", 1 << 8), (0xC5, ">H", 1 << 16), (0xC6, ">I", 1 << 32))) + bytes(v)
149 if isinstance(v, list):
150 return _mp_len(len(v), 0x90, 15, ((0xDC, ">H", 1 << 16), (0xDD, ">I", 1 << 32))) + b"".join(map(mp_dump, v))
151 if isinstance(v, dict):
152 head = _mp_len(len(v), 0x80, 15, ((0xDE, ">H", 1 << 16), (0xDF, ">I", 1 << 32)))
153 return head + b"".join(mp_dump(k) + mp_dump(x) for k, x in v.items())
154 raise TypeError(f"cannot write {type(v).__name__} as msgpack")
155
156
157# ---- the PAL ELF of a pipeline binary ----
158
159_SH = "<IIQQQQIIQQ"
160
161
162class Elf:
163 """An ELF64 with no program headers (what the AMD driver's pipeline binary is): sections kept in file order,
164 rewritten with any section's data replaced."""
165
166 def __init__(self, data):
167 data = bytes(data)
168 if data[:4] != b"\x7fELF" or data[4] != 2 or data[5] != 1:
169 raise Unavailable("the pipeline binary is not a 64-bit little-endian ELF (not an AMD PAL binary)")
170 if struct.unpack_from("<H", data, 0x12)[0] != 0xE0:
171 raise Unavailable("the pipeline binary is not an AMDGPU ELF")
172 if struct.unpack_from("<H", data, 0x38)[0]:
173 raise ValueError("an ELF with program headers is not supported")
174 self.head = bytearray(data[:64])
175 shoff = struct.unpack_from("<Q", data, 0x28)[0]
176 shentsize, shnum, self.shstrndx = struct.unpack_from("<HHH", data, 0x3A)
177 self.hdrs = [list(struct.unpack_from(_SH, data, shoff + i * shentsize)) for i in range(shnum)]
178 self.data = [bytearray(data[h[4]:h[4] + h[5]]) if h[1] != 8 else bytearray() for h in self.hdrs]
179 strtab = self.data[self.shstrndx]
180 self.names = [strtab[h[0]:strtab.index(b"\0", h[0])].decode() for h in self.hdrs]
181
182 def index(self, name):
183 if name not in self.names:
184 raise ValueError(f"no {name} section")
185 return self.names.index(name)
186
187 def symbols(self):
188 """[(name, value, size, symtab entry index)] of .symtab."""
189 st = self.index(".symtab")
190 strs = self.data[self.hdrs[st][6]]
191 out = []
192 for i in range(len(self.data[st]) // 24):
193 name, _info, _other, _shndx, value, size = struct.unpack_from("<IBBHQQ", self.data[st], i * 24)
194 out.append((strs[name:strs.index(b"\0", name)].decode(), value, size, i))
195 return out
196
197 def set_symbol_size(self, entry, size):
198 struct.pack_into("<Q", self.data[self.index(".symtab")], entry * 24 + 16, size)
199
200 def to_bytes(self):
201 order = sorted((i for i in range(1, len(self.hdrs)) if self.hdrs[i][1] != 8), key=lambda i: self.hdrs[i][4])
202 out = bytearray(self.head)
203 for i in order:
204 self.hdrs[i][4] = len(out)
205 self.hdrs[i][5] = len(self.data[i])
206 out += self.data[i]
207 while len(out) % 8:
208 out += b"\0"
209 struct.pack_into("<Q", out, 0x28, len(out))
210 for h in self.hdrs:
211 out += struct.pack(_SH, *h)
212 return bytes(out)
213
214 # The PAL metadata note: one NT_AMDGPU_METADATA (32) with owner "AMDGPU" and a msgpack desc.
215 def metadata(self):
216 note = self.data[self.index(".note")]
217 namesz, descsz, typ = struct.unpack_from("<III", note, 0)
218 if typ != 32 or note[12:12 + namesz].rstrip(b"\0") != b"AMDGPU":
219 raise Unavailable("no AMDGPU metadata note (not a PAL binary)")
220 at = 12 + (namesz + 3) // 4 * 4
221 return mp_load(note, at)[0]
222
223 def set_metadata(self, meta):
224 desc = mp_dump(meta)
225 name = b"AMDGPU\0"
226 note = struct.pack("<III", len(name), len(desc), 32) + name + b"\0" * (-len(name) % 4) + desc
227 self.data[self.index(".note")] = bytearray(note + b"\0" * (-len(note) % 4))
228
229
230def read_binaries(path):
231 """vk_harness's VKH_BINARY_OUT file -> [(key size, 32 key bytes, data)]."""
232 with open(path, "rb") as f:
233 d = f.read()
234 n, at, out = struct.unpack_from("<I", d, 0)[0], 4, []
235 for _ in range(n):
236 ks = struct.unpack_from("<I", d, at)[0]
237 key = d[at + 4:at + 36]
238 size = struct.unpack_from("<Q", d, at + 36)[0]
239 out.append((ks, key, d[at + 44:at + 44 + size]))
240 at += 44 + size
241 return out
242
243
244def write_binaries(path, bins):
245 with open(path, "wb") as f:
246 f.write(struct.pack("<I", len(bins)))
247 for ks, key, data in bins:
248 f.write(struct.pack("<I", ks) + key + struct.pack("<Q", len(data)) + data)
249
250
251def ps_stage(meta):
252 """The pixel hardware stage's metadata map (amdpal.pipelines[0].hardware_stages[.ps])."""
253 try:
254 return meta["amdpal.pipelines"][0][".hardware_stages"][".ps"]
255 except (KeyError, IndexError, TypeError):
256 raise Unavailable("the PAL metadata has no pixel hardware stage") from None
257
258
259_REG = re.compile(r"(?<![\w.])([vs])(?:(\d+)|\[\d+:(\d+)\])(?![\w.])")
260
261
262def regs_used(lines):
263 """(VGPRs, SGPRs) the lines name: one past the highest v<N> / v[a:b] and s<N> / s[a:b]."""
264 top = {"v": 0, "s": 0}
265 for line in lines:
266 for kind, single, last in _REG.findall(line.split(";", 1)[0]):
267 top[kind] = max(top[kind], int(last or single) + 1)
268 return top["v"], top["s"]
269
270
271def set_meta(pipe, path, value):
272 """Set one value in the pipeline's metadata map: path is '/'-separated keys from amdpal.pipelines[0] (list
273 indices as numbers), e.g. ".graphics_registers/.spi_ps_input_cntl/0/.fp16_interp_mode"."""
274 keys = [int(k) if k.isdigit() else k for k in path.split("/") if k]
275 node = pipe
276 for k in keys[:-1]:
277 node = node[k]
278 if keys[-1] not in node if isinstance(node, dict) else not 0 <= keys[-1] < len(node):
279 raise ValueError(f"no metadata entry {path!r}")
280 old = node[keys[-1]]
281 if isinstance(old, F32):
282 value = F32(value)
283 node[keys[-1]] = value
284
285
286def patch_ps(elf_bytes, code, lines=(), sets=()):
287 """The ELF with `_amdgpu_ps_main` replaced by `code` (raw instruction bytes), padded with s_code_end, the pixel
288 stage's VGPR/SGPR counts raised to cover the registers `lines` name, and each (path, value) of `sets` written
289 into the metadata (set_meta). `_amdgpu_ps_main` must be the last function of .text (it is in the AMD driver's
290 binaries)."""
291 elf = Elf(elf_bytes)
292 syms = {s[0]: s for s in elf.symbols()}
293 if PS_SYMBOL not in syms:
294 raise Unavailable(f"no {PS_SYMBOL} in the pipeline binary")
295 _, start, _, entry = syms[PS_SYMBOL]
296 if any(v > start for n, v, _s, _e in syms.values() if n and n != PS_SYMBOL):
297 raise ValueError(f"{PS_SYMBOL} is not the last function of .text")
298 ti = elf.index(".text")
299 code = bytes(code) + S_CODE_END * ((-len(code) % 64) // 4 + 64) # the hardware prefetches past the end
300 elf.data[ti] = bytearray(elf.data[ti][:start]) + bytearray(code)
301 elf.set_symbol_size(entry, len(code) - 64 * 4)
302 v, s = regs_used(lines)
303 meta = elf.metadata()
304 stage = ps_stage(meta)
305 changed = bool(sets)
306 for path, value in sets:
307 set_meta(meta["amdpal.pipelines"][0], path, value)
308 if v > stage.get(".vgpr_count", 0) or s > stage.get(".sgpr_count", 0):
309 stage[".vgpr_count"] = max(stage.get(".vgpr_count", 0), v)
310 stage[".sgpr_count"] = max(stage.get(".sgpr_count", 0), s)
311 changed = True
312 if changed:
313 elf.set_metadata(meta)
314 return elf.to_bytes()
315
316
317def ps_code(elf_bytes):
318 """(start, bytes) of `_amdgpu_ps_main` in .text (to the end of .text, s_code_end padding included)."""
319 elf = Elf(elf_bytes)
320 syms = {s[0]: s for s in elf.symbols()}
321 start = syms[PS_SYMBOL][1]
322 return start, bytes(elf.data[elf.index(".text")][start:])
323
324
325def is_wave64(elf_bytes):
326 """The pixel stage's wave size from its first instruction, s_version (UC_VERSION_W64_BIT)."""
327 _, code = ps_code(elf_bytes)
328 word = struct.unpack_from("<I", code, 0)[0]
329 if word >> 23 != 0x161: # SOPK opcode 1 (s_version) in GFX10: 0xB080xxxx
330 return None
331 return bool(word & W64_BIT)
332
333
334# ---- templates ----
335
336VS_TRI = """\
337 OpCapability Shader
338 OpMemoryModel Logical GLSL450
339 OpEntryPoint Vertex %main "main" %vid %pos %out0 %out1
340 OpDecorate %vid BuiltIn VertexIndex
341 OpDecorate %pos BuiltIn Position
342 OpDecorate %out0 Location 0
343 OpDecorate %out1 Location 1
344 %void = OpTypeVoid
345 %fn = OpTypeFunction %void
346 %uint = OpTypeInt 32 0
347 %int = OpTypeInt 32 1
348 %float = OpTypeFloat 32
349 %v4 = OpTypeVector %float 4
350 %p_in = OpTypePointer Input %int
351 %p_out = OpTypePointer Output %v4
352 %u3 = OpConstant %uint 3
353 %arr = OpTypeArray %v4 %u3
354 %p_arr = OpTypePointer Function %arr
355 %p_v4 = OpTypePointer Function %v4
356 %fm1 = OpConstant %float -1
357 %f0 = OpConstant %float 0
358 %f1 = OpConstant %float 1
359 %f2 = OpConstant %float 2
360 %f3 = OpConstant %float 3
361 %p0 = OpConstantComposite %v4 %fm1 %fm1 %f0 %f1
362 %p1 = OpConstantComposite %v4 %f3 %fm1 %f0 %f1
363 %p2 = OpConstantComposite %v4 %fm1 %f3 %f0 %f1
364 %pa = OpConstantComposite %arr %p0 %p1 %p2
365 %a0 = OpConstantComposite %v4 %f0 %f0 %f0 %f1
366 %a1 = OpConstantComposite %v4 %f2 %f0 %f0 %f1
367 %a2 = OpConstantComposite %v4 %f0 %f2 %f0 %f1
368 %aa = OpConstantComposite %arr %a0 %a1 %a2
369 %b0 = OpConstantComposite %v4 %f0 %f0 %f0 %f0
370 %b1 = OpConstantComposite %v4 %f2 %f0 %f0 %f0
371 %b2 = OpConstantComposite %v4 %f0 %f2 %f0 %f0
372 %ba = OpConstantComposite %arr %b0 %b1 %b2
373 %vid = OpVariable %p_in Input
374 %pos = OpVariable %p_out Output
375 %out0 = OpVariable %p_out Output
376 %out1 = OpVariable %p_out Output
377 %main = OpFunction %void None %fn
378 %e = OpLabel
379 %vp = OpVariable %p_arr Function
380 %va = OpVariable %p_arr Function
381 %vb = OpVariable %p_arr Function
382 OpStore %vp %pa
383 OpStore %va %aa
384 OpStore %vb %ba
385 %i = OpLoad %int %vid
386 %xp = OpAccessChain %p_v4 %vp %i
387 %xv = OpLoad %v4 %xp
388 OpStore %pos %xv
389 %yp = OpAccessChain %p_v4 %va %i
390 %yv = OpLoad %v4 %yp
391 OpStore %out0 %yv
392 %zp = OpAccessChain %p_v4 %vb %i
393 %zv = OpLoad %v4 %zp
394 OpStore %out1 %zv
395 OpReturn
396 OpFunctionEnd
397"""
398
399_PS_HEAD = """\
400 OpCapability Shader
401 OpMemoryModel Logical GLSL450
402 OpEntryPoint Fragment %main "main" {ios}
403 OpExecutionMode %main OriginUpperLeft
404 OpDecorate %out Location 0
405{decor} %void = OpTypeVoid
406 %fn = OpTypeFunction %void
407 %float = OpTypeFloat 32
408 %v4 = OpTypeVector %float 4
409 %p_in = OpTypePointer Input %v4
410 %p_out = OpTypePointer Output %v4
411 %out = OpVariable %p_out Output
412"""
413
414TEMPLATES = {
415 # mrt0 = a constant: no inputs at all (exports, EXEC, helper lanes)
416 "const": _PS_HEAD.format(ios="%out", decor="") + """\
417 %f1 = OpConstant %float 1
418 %c = OpConstantComposite %v4 %f1 %f1 %f1 %f1
419 %main = OpFunction %void None %fn
420 %e = OpLabel
421 OpStore %out %c
422 OpReturn
423 OpFunctionEnd
424""",
425 # mrt0 = location 0 + location 1: two smooth vec4 parameters, perspective barycentrics
426 "interp2": _PS_HEAD.format(ios="%in0 %in1 %out", decor="""\
427 OpDecorate %in0 Location 0
428 OpDecorate %in1 Location 1
429""") + """\
430 %in0 = OpVariable %p_in Input
431 %in1 = OpVariable %p_in Input
432 %main = OpFunction %void None %fn
433 %e = OpLabel
434 %a = OpLoad %v4 %in0
435 %b = OpLoad %v4 %in1
436 %s = OpFAdd %v4 %a %b
437 OpStore %out %s
438 OpReturn
439 OpFunctionEnd
440""",
441}
442
443
444def spirv(path_or_text, out, work):
445 """A .spv as is; SPIR-V assembly (a .spvasm path or template text) through spirv-as."""
446 if not path_or_text.lstrip().startswith("Op") and path_or_text.endswith(".spv"):
447 return path_or_text
448 src = path_or_text
449 if not path_or_text.lstrip().startswith("Op"):
450 with open(path_or_text, encoding="utf-8") as f:
451 src = f.read()
452 asm_path = os.path.join(work, os.path.basename(out) + "asm")
453 with open(asm_path, "w", encoding="utf-8", newline="\n") as f:
454 f.write(src)
455 try:
456 r = subprocess.run(["spirv-as", "--target-env", "vulkan1.2", asm_path, "-o", out], capture_output=True,
457 text=True)
458 except OSError:
459 raise Unavailable("spirv-as is not on PATH") from None
460 if r.returncode:
461 raise ValueError(f"spirv-as: {r.stderr.strip()}")
462 return out
463
464
465# ---- running ----
466
467def harness(build):
468 for name in ("vk_harness.exe", "vk_harness"):
469 p = os.path.join(build, name)
470 if os.path.exists(p):
471 return p
472 raise Unavailable(f"no vk_harness in {build}")
473
474
475def run_harness(exe, vs, ps, out_raw, size, env_extra):
476 env = dict(os.environ, **env_extra)
477 r = subprocess.run([exe, vs, ps, out_raw, str(size[0]), str(size[1])], capture_output=True, text=True, env=env)
478 if r.returncode == 77:
479 raise Unavailable(r.stderr.strip().splitlines()[-1] if r.stderr.strip() else "vk_harness: unsupported")
480 return r
481
482
483def assemble(lines, mcpu, wave64, work):
484 """Raw instruction bytes of the lines, through AMD clang (an amdpal object, its .text)."""
485 from hw_oracle import runner
486 try:
487 clang = runner.find_clang()
488 except runner.Unavailable as e:
489 raise Unavailable(str(e)) from None
490 s = os.path.join(work, "ps.s")
491 o = os.path.join(work, "ps.o")
492 with open(s, "w", encoding="utf-8", newline="\n") as f:
493 f.write(".text\n" + "".join(f" {ln}\n" for ln in lines))
494 flags = ["-mwavefrontsize64"] if wave64 else []
495 r = subprocess.run([clang, "--target=amdgcn-amd-amdpal", f"-mcpu={mcpu}", *flags, "-c", s, "-o", o],
496 capture_output=True, text=True)
497 if r.returncode:
498 raise ValueError("the assembler rejected the code:\n" + r.stderr.strip())
499 with open(o, "rb") as f:
500 obj = Elf(f.read())
501 if any(n.startswith(".rel") and n.endswith(".text") for n in obj.names):
502 raise ValueError("the code needs relocations (a symbol it does not define); use plain branches and literals")
503 return bytes(obj.data[obj.index(".text")])
504
505
506def read_lines(path):
507 lines = []
508 with open(path, encoding="utf-8") as f:
509 for ln in f:
510 ln = ln.split(";", 1)[0].split("//", 1)[0].strip()
511 if ln:
512 lines.append(ln)
513 return lines
514
515
516def pixels(raw_path, size):
517 with open(raw_path, "rb") as f:
518 d = f.read()
519 n = size[0] * size[1]
520 if len(d) != 16 * n:
521 raise RuntimeError(f"readback is {len(d)} bytes, expected {16 * n}")
522 return [list(struct.unpack_from("<4I", d, 16 * i)) for i in range(n)]
523
524
525class Oracle:
526 """One template pipeline, built once; run() patches its pixel shader and draws."""
527
528 def __init__(self, build, vs=None, ps=None, template="interp2", size=(8, 8), mcpu="gfx1036", work=None):
529 self.exe = harness(build)
530 self.size = tuple(size)
531 self.mcpu = mcpu
532 self._tmp = None if work else tempfile.TemporaryDirectory(prefix="ps_oracle_")
533 self.work = work or self._tmp.name
534 os.makedirs(self.work, exist_ok=True)
535 self.vs = spirv(vs or VS_TRI, os.path.join(self.work, "vs.spv"), self.work)
536 if ps is None and template not in TEMPLATES:
537 raise ValueError(f"unknown template {template!r} (known: {', '.join(TEMPLATES)})")
538 self.ps = spirv(ps or TEMPLATES[template], os.path.join(self.work, "ps.spv"), self.work)
539 out_bin = os.path.join(self.work, "template.bin")
540 r = run_harness(self.exe, self.vs, self.ps, os.path.join(self.work, "template.raw"), self.size,
541 {"VKH_BINARY_OUT": out_bin})
542 if r.returncode or not os.path.exists(out_bin):
543 raise RuntimeError("vk_harness could not build the template:\n" + r.stderr.strip()[-800:])
544 self.device = next((m.group(1) for m in re.finditer(r"device[:=]\s*(.+)", r.stderr)), "")
545 self.bins = read_binaries(out_bin)
546 if len(self.bins) != 1:
547 raise Unavailable(f"the pipeline came back as {len(self.bins)} binaries (expected one PAL ELF)")
548 self.elf = self.bins[0][2]
549 self.meta = Elf(self.elf).metadata()
550 self.wave64 = is_wave64(self.elf)
551 self.template_pixels = pixels(os.path.join(self.work, "template.raw"), self.size)
552
553 def show(self):
554 """The template's pixel-shader ISA (llvm-objdump) and the SPI part of its metadata."""
555 from hw_oracle import runner
556 path = os.path.join(self.work, "template.elf")
557 with open(path, "wb") as f:
558 f.write(self.elf)
559 start, code = ps_code(self.elf)
560 lines = [f"pixel stage: wave{64 if self.wave64 else 32}, {len(code)} bytes from 0x{start:x}"]
561 try:
562 objdump = os.path.join(os.path.dirname(runner.find_clang()), "llvm-objdump" + (".exe" if os.name == "nt" else ""))
563 r = subprocess.run([objdump, "-d", f"--mcpu={self.mcpu}", f"--start-address=0x{start:x}", path],
564 capture_output=True, text=True)
565 lines += [ln for ln in r.stdout.splitlines() if ln.strip() and "s_code_end" not in ln]
566 except (runner.Unavailable, OSError) as e:
567 lines.append(f"(no disassembly: {e})")
568 pipe = self.meta["amdpal.pipelines"][0]
569 regs = pipe.get(".graphics_registers", {})
570 keep = {k: v for k, v in regs.items() if k.startswith((".spi_ps", ".spi_shader_col", ".spi_baryc",
571 ".spi_interp", ".ps_", ".db_shader"))}
572 lines.append("graphics registers: " + json.dumps(keep, indent=1, default=str))
573 lines.append("pixel stage: " + json.dumps(ps_stage(self.meta), indent=1, default=str))
574 return "\n".join(lines)
575
576 def run(self, lines, sets=()):
577 """Every pixel's mrt0 words (row-major, size[0] x size[1]) with the pixel shader replaced by `lines` and the
578 metadata changes `sets` ((path, value) pairs, see set_meta) applied."""
579 code = assemble(lines, self.mcpu, self.wave64, self.work)
580 patched = patch_ps(self.elf, code, lines, sets)
581 path = os.path.join(self.work, "patched.bin")
582 write_binaries(path, [(self.bins[0][0], self.bins[0][1], patched)])
583 raw = os.path.join(self.work, "patched.raw")
584 if os.path.exists(raw):
585 os.remove(raw)
586 r = run_harness(self.exe, self.vs, self.ps, raw, self.size, {"VKH_BINARY_IN": path})
587 if r.returncode or not os.path.exists(raw):
588 raise RuntimeError(f"vk_harness exited {r.returncode} with the patched binary:\n" + r.stderr.strip()[-800:])
589 return pixels(raw, self.size)
590
591 def close(self):
592 if self._tmp:
593 self._tmp.cleanup()
594
595
596def summarize(px, size):
597 """Distinct mrt0 words with how many pixels and the first pixel (x, y) that has them."""
598 seen = {}
599 for i, w in enumerate(px):
600 k = tuple(w)
601 if k not in seen:
602 seen[k] = [0, (i % size[0], i // size[0])]
603 seen[k][0] += 1
604 return seen
605
606
607def main(argv=None):
608 ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
609 ap.add_argument("--build", required=True, help="runtime build folder with vk_harness")
610 ap.add_argument("--template", default="interp2", help=f"one of {', '.join(TEMPLATES)} (default interp2)")
611 ap.add_argument("--vs", help="vertex shader (.spv or SPIR-V assembly) instead of the built-in one")
612 ap.add_argument("--ps", help="template pixel shader (.spv or SPIR-V assembly) instead of --template")
613 ap.add_argument("--asm", help="the pixel-shader ISA to run (one instruction per line, ; comments)")
614 ap.add_argument("--size", nargs=2, type=int, default=(8, 8), metavar=("W", "H"))
615 ap.add_argument("--mcpu", default="gfx1036")
616 ap.add_argument("--show-template", action="store_true", help="print the template's ISA and SPI setup")
617 ap.add_argument("--set", action="append", default=[], metavar="PATH=JSON",
618 help="change the pipeline metadata, e.g. .graphics_registers/.spi_ps_input_cntl/0/.fp16_interp_mode=true")
619 ap.add_argument("--json", help="write {device, wave, size, pixels} here")
620 a = ap.parse_args(argv)
621 if not (a.asm or a.show_template):
622 ap.error("nothing to do: give --asm and/or --show-template")
623 if not all(0 < n <= 4096 for n in a.size):
624 ap.error("--size must be 1..4096")
625 try:
626 lines = read_lines(a.asm) if a.asm else None
627 sets = []
628 for item in a.set:
629 path, eq, val = item.partition("=")
630 if not eq:
631 raise ValueError(f"--set {item!r}: expected PATH=JSON")
632 sets.append((path, json.loads(val)))
633 o = Oracle(a.build, a.vs, a.ps, a.template, a.size, a.mcpu)
634 except Unavailable as e:
635 print(f"ps_oracle unavailable: {e}", file=sys.stderr)
636 return 77
637 except (OSError, ValueError, RuntimeError) as e:
638 print(f"ps_oracle: {e}", file=sys.stderr)
639 return 2
640 try:
641 print(f"pixel stage wave{64 if o.wave64 else 32}{' on ' + o.device if o.device else ''}")
642 if a.show_template:
643 print(o.show())
644 if lines is None:
645 return 0
646 try:
647 px = o.run(lines, sets)
648 except (ValueError, KeyError, IndexError, TypeError) as e:
649 print(f"ps_oracle: {e}", file=sys.stderr)
650 return 2
651 except RuntimeError as e:
652 print(f"ps_oracle: {e}", file=sys.stderr)
653 return 1
654 for words, (count, xy) in summarize(px, a.size).items():
655 print(f"{count:6d} px, first at {xy}: " + " ".join(f"0x{w:08x}" for w in words))
656 if a.json:
657 with open(a.json, "w", encoding="utf-8", newline="\n") as f:
658 json.dump({"device": o.device, "wave": 64 if o.wave64 else 32, "size": list(a.size), "pixels": px},
659 f, indent=1)
660 return 0
661 finally:
662 o.close()
663
664
665if __name__ == "__main__":
666 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
667 sys.stdout.reconfigure(errors="replace")
668 except (AttributeError, ValueError, OSError):
669 pass
670 sys.exit(main())