diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 07db247b06..588f5a1333 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -793,13 +793,21 @@ the game's present entry point (`PresentX`; the DXGI factory/swapchain and the p 152b9cde, `src/amd/vulkan/radv_physical_device.c`, `requiredSubgroupSizeStages`; older Mesa reported compute only). NVIDIA lists every stage but only size 32, so a native wave64 shader cannot get 64 there. Vertex and geometry stages are in neither list. + - **Wave32 vertex shaders** (`wave32_halves` in the index): the AMD Windows driver runs the vertex stage + 64-wide (measured on an RX 7600, 26.11.2: 62 to 64 vertices per subgroup, sizes 32..64, VERTEX not requirable), + so a wave32 VS shared one subgroup with a second wave's worth of vertices: lanes 32..63 reported lane 32, + `v_readfirstlane`, ballots, votes and `s_bcnt1` covered 64 vertices, `ds_bpermute` read the other half and a + write to `exec_lo` did not reach lanes 32..63. The translator now keeps each wave in its own 32 subgroup lanes + (docs/design.md, "Wave32 vertex shaders on wider subgroups"), and the + decision is `halves` there: nothing is required and nothing is logged. A device that can run the stage below + 32 lanes still gets `unavailable` (or `device_default` when its default is 32). - **A size the device cannot give** is logged once per stage with the first shader's name (and again at 10, 100, 1000 shaders of that stage): `[rt] d3d12: () is a 64-wide shader but this device cannot require that subgroup size ...`. For compute and mesh the fix is the build, `--wave64-emulate` (`make_game.py --wave64-emulate auto` picks it for this GPU); a wave64 vertex, geometry or pixel shader has no emulation yet (the ~10,000 wave64 pixel shaders are the open case on NVIDIA, SHADER-10). - **Test:** `subgroup_size_test` (CPU) checks the decision against AMD-like, NVIDIA-like and old-RADV - properties and the resulting create-info chain; `d3d12_subgroup_test` (GPU) runs `cs_w64x_readlane` natively + properties (and a halves VS on each, and on a device with sizes below 32) and the resulting create-info chain; `d3d12_subgroup_test` (GPU) runs `cs_w64x_readlane` natively and with `--wave64-emulate`, and `cs_wqm_w32`, through D3D12 PSOs and compares the read-back words. Known gaps: set 0 in pipelines (the device keeps the bindless set, but no pipeline declares or binds it yet) and diff --git a/docs/design.md b/docs/design.md index 4f6a31a407..c231210486 100644 --- a/docs/design.md +++ b/docs/design.md @@ -229,6 +229,7 @@ How the generated SPIR-V expects the runtime to work: | Piece | Contract | |---|---| | Execution model | One invocation = one lane. A wave = a subgroup, so cross-lane ops (`ds_swizzle`, `v_permlane*`, `v_readlane`/`v_writelane`, `v_mbcnt`) become subgroup shuffles. **Requires subgroup size == wave size** (wave32 maps directly onto NVIDIA GPUs; wave64 shaders need a 64-wide subgroup or emulation). `v_readlane_b32`/`v_writelane_b32` mask the lane select with 63 in wave64 (`S1[5:0]`) and 31 in wave32 (`S1[4:0]`); until SHADER-52 both used 63, so a wave32 select ≥ 32 pointed past a 32-wide subgroup. GPU-checked with `cs_w32_lane_wrap.asm` (lane 40 → 8). | +| Wave32 vertex shaders on wider subgroups | The tested RX 7600 Windows driver omits VERTEX from `requiredSubgroupSizeStages` and runs the vertex stage 64-wide (RX 7600, 26.11.2: `w32_vs_halves.py` packs 62 to 64 vertices per subgroup). A wave32 VS (`Gen.halves`, the default; `--no-wave32-halves` for the old translation; selected automatically for MoltenVK vertex functions and devices reporting no vertex subgroup ballot support) therefore treats subgroup lanes 32k..32k+31 as one wave: the wave lane is the subgroup lane mod 32 (`v_mbcnt`, `v_writelane`, EXEC/VCC half writes, lane-indexed buffer addresses), a mask read as a whole is this wave's word of a ballot (`s_bcnt1`, `s_ff1`, `v_mbcnt` of a mask, the vote of `s_cbranch_vccz/execz`, SCC of a mask op), `v_readfirstlane` is the lowest set bit of that word, and a shuffle source (`v_readlane`, `ds_bpermute`, `ds_permute`, and the quad, swizzle and permlane forms, which already stay in 32 lanes) is `(lane & 31) | (subgroup lane & ~31)`. On a 32-wide subgroup that is word 0 and base 0, the plain translation; on 64 each half has its own lane indices, ballots and shuffle sources; below 32 nothing changes. The index marks the entry `wave32_halves` and the runtime decides `halves` (nothing required, nothing logged) where every size the device runs is at least 32 (`runtime/src/subgroup_size.h`). Confirmed: `tests/semantic/test_wave32_vs_halves.py` runs four programs (lane count and first lane; ballot rank, count and first lane; `v_readlane` 5/31 and `ds_bpermute`; a `s_cbranch_vccz` vote over an SGPR write and an `exec_lo` write) on the wave interpreter at 32 and 64 invocations against an independent two-wave32 model (equal; `--no-wave32-halves` equal at 32, wrong at 64), and `runtime/test/shaders/w32_vs_halves.py` draws the same four as `vs_w32_*` fixtures (960 vertices) on an AMD Radeon RX 7600 (driver 26.11.2, Windows 10), checked against what every wave32 must satisfy whatever the packing: before, 15 of 16 subgroups failed (64 vertices per key, lane 32 repeated, bpermute and `exec_lo` wrong in lanes 32..63); after, 31 waves of at most 32 vertices, 0 problems, with and without `VK_LAYER_KHRONOS_validation`. Cost: a VS that reads a mask as a whole, votes or calls `v_readfirstlane` now also reads `SubgroupLocalInvocationId`, which a Metal vertex function cannot (hence the MoltenVK fallback). Scalar-written VCC consumption is a separate, pre-existing limitation. Geometry and pixel shaders keep their existing translation. Hardware validation here covers the RX 7600; subgroup size 128 and Metal execution remain unverified. | | DPP | VOP1/VOP2 `_dpp` applies to src0. DPP16 controls (`quad_perm`, `row_shl/shr/ror/share/xmask/mirror/half_mirror`) and DPP8 (`dpp8` + `fi`) select the source lane, then `row_mask` (one bit per 16-lane row) and `bank_mask` (one bit per 4-lane bank) decide which destination lanes update. A lane whose row/bank is off is not written. A source lane outside the row is invalid: `bound_ctrl` 1 uses 0 as src0, otherwise the lane is not written. A source lane inactive under EXEC is used when `fi` is 1; otherwise `bound_ctrl` decides. DPP8 always writes an enabled lane: `fi` 1 reads the inactive source, `fi` 0 uses 0. DPP16/8 never leaves its 16/8-lane group, so this is exact on every subgroup at least that wide; under `--wave64-emulate` the exchange goes through the workgroup buffer like the other cross-lane ops. GPU-checked with `runtime/test/shaders/cs_dpp*.asm` on an RTX 3070 and hardware-measured on an RX 6800. On an RX 6700 XT (gfx1031), `tools/crosslane_fuzz.py --dpp-sweep --oracle hw` checks every DPP16 control × `bound_ctrl` × `fi`, every `row_mask`/`bank_mask` pair and the DPP8 selects in wave32 and wave64: 14,412 cases, all matching these rules (BUILD-162, `docs/shader_validation.md` FUZZ-7). Semantics from the RDNA2 ISA, AMD LLVM modifier syntax and the GPUOpen DPP notes. | | EXEC | A per-invocation `active` flag. VALU writes and exports are masked by it, scalar ops aren't, and `v_cmpx`, saveexec and EXEC writes update it. A pixel lane still inactive at the end is discarded. Measured on native gfx1100 (8 threads): a `v_mov_b32` under `EXEC=0x0F` leaves the other lanes untouched, `EXEC=0` writes nothing, a store writes only active lanes and `v_cmpx_gt_u32` narrows EXEC (4 of 4 cases); note that AMD clang 20 rejects `v_add_co_u32`, `v_sub_co_u32`, `v_add_co_ci_u32` and `v_mad_u64_u32` for `gfx1100`, `gfx1101` and `gfx1102`, so this toolchain could not reproduce the RX 7600 result below, which leaves open whether those parts support the opcodes and says only that they could not be assembled here. A pixel lane that was inactive at the last `exp ... vm` it executed is discarded, and on a path without one, a lane inactive at the end (EXEC is kept at the export only where a path can write it afterwards). **The `vm` rule is from the RDNA2 ISA reference guide (30-November-2020, §11.1 and §11.2.1: EXEC at the export is the valid mask and the final one sent is used), not measured on hardware**; checked on the CPU by `tests/semantic/test_export_valid_mask.py`. VALU scalar lane-mask destinations (`v_cmp_*`, `v_add_co_u32`, `v_add_co_ci_u32`, `v_sub_co_u32`, `v_sub_co_ci_u32`, `v_subrev_co_u32`, `v_subrev_co_ci_u32`, `v_mad_u64_u32`, `v_mad_i64_i32`) write 0 for lanes off in EXEC (`SDST[lane] = EXEC[lane] ? bit : 0`, AMD RDNA2 ISA). Until 2026-11-22 the six `*_co_*` ops and `v_mad_u64_u32`/`v_mad_i64_i32` did not AND the carry/sign bit with `active`, so inactive lanes leaked 1 bits into `VCC`/SGPR masks (`s_bcnt1`, `s_cbranch_vccz`, `v_cndmask_b32`). Checked on the CPU by `tests/semantic/test_carry_exec_mask.py` (wave32, wave64, and `--wave64-emulate` structure), and GPU-verified on native RDNA2 (gfx1036, AMD Radeon Graphics) with partial EXEC masks (inactive lanes write 0 in sdst for `v_add_co_u32` and `v_mad_u64_u32`). Checked on the CPU by `tests/semantic/test_carry_exec_mask.py` (wave32, wave64, and `--wave64-emulate` structure), and **hardware-verified on an AMD RX 7600 (gfx1102)** with `v_add_co_u32` and `v_add_co_ci_u32` carrying on every active lane: VCC reads `0xffffffff` with full EXEC, `0x0000ffff` for the mask `0x0000ffff` and `0xaaaaaaaa` for `0xaaaaaaaa` in wave32, `vcc_lo = 0x0000ffff` with `vcc_hi = 0x0000000f` for the same partial mask in wave64, and `0` when EXEC is 0 even with VCC preloaded to all ones; with one carrying lane under mask `0x0000ffff` VCC is `0x00000001`, and `v_sub_co_u32`/`v_subrev_co_u32` with a borrow under that mask give `0x0000ffff` too. The `*_co_ci_` forms, `v_mad_u64_u32` and `v_mad_i64_i32` share the same path but were not measured separately.; also GPU-verified on native RDNA2 (gfx1036, AMD Radeon Graphics) with partial EXEC masks (inactive lanes write 0 in sdst for `v_add_co_u32` and `v_mad_u64_u32`). The `*_co_ci_` forms, `v_mad_u64_u32` and `v_mad_i64_i32` share the same path but were not measured separately. | | `s_*_saveexec_b32/b64`, `s_andn1/andn2_wrexec_b32/b64` | RDNA2 ISA SOP1. saveexec: `D = EXEC; EXEC = f(S0, EXEC); SCC = (EXEC != 0)`. wrexec: `EXEC = f(S0, EXEC); D = EXEC`. `f` is one of `and`, `or`, `xor`, `andn1` (`~S0 & EXEC`), `andn2` (`S0 & ~EXEC`), `orn1`, `orn2`, `nand`, `nor`, `xnor`, the table in `Gen.EXEC_LOGIC`. The definitions match `tools/cf_ref.py` `_SAVEEXEC`, the FUZZ-8 model. Each invocation holds its own lane's bit (0 or ~0), so `f` is the bitwise op on that bit. A lane EXEC had off becomes active when `f` gives 1 for it (`nand`, `nor`, `orn1`, `orn2`, `xnor`, ...), as on hardware, and SCC is the wave vote. Until 2026-11-22 only `and`/`or`/`andn2_saveexec` and `andn2_wrexec` were translated. CPU-checked by `tests/semantic/test_saveexec_variants.py` (all ten saveexec kinds in wave32 and wave64, both wrexec kinds, partial EXEC and S0, an empty result, every lane against `cf_ref._SAVEEXEC`) and by `tools/cf_diff.py` (300 programs × wave32/64 still pass). **Not GPU-verified** for the seven new kinds. | @@ -326,7 +327,7 @@ How the generated SPIR-V expects the runtime to work: | `ds_swizzle_b32` | An active destination reads the selected source lane's VGPR. If EXEC disables that source, the read returns zero; a disabled destination keeps its prior value. The [hardware measurements](shader_validation.md#hardware-oracle-for-the-lds-programs---oracle-hw) confirm the disabled-source result on gfx1036 and gfx1150. In the seven-invocation CPU fixture, lane 6 selects lane 7, which is absent. The translator returns zero in that case; the corresponding result on hardware is unverified. The fixture exercises `QUAD_PERM` and `SWAP` in `test_ds_permute.py`. | | Wave64 handling | Wave size is detected per shader from the code (64-bit EXEC writes, `exec_hi`, `v_mbcnt_hi`, `*_saveexec_b64`/`*_wrexec_b64`, and 64-bit lane-mask SOP ops `s_bcnt[01]_i32_b64` / `s_ff[01]_i32_b64` / `s_wqm_b64` / `s_bfm_b64` even when the mask is an ordinary SGPR pair; mesh shaders are always wave64). Wave size comes from the sidecar `fssm/.fssm` header flags word `u32[0xD4]` bit 5 (`0x20` = wave32, `0` = wave64; `fssm_header.wave_size()`), cross-checked against wave64/wave32 code markers (`WAVE64_RE` / `WAVE32_RE`: a contradicting header and code listing raises `Unsupported`), and falls back to the code-marker heuristic (64-bit EXEC/VCC writes, `exec_hi`, `v_mbcnt_hi`, `*_saveexec_b64`/`*_wrexec_b64`, and 64-bit lane-mask SOP ops `s_bcnt[01]_i32_b64` / `s_ff[01]_i32_b64` / `s_wqm_b64` / `s_bfm_b64`, plus wave64 for mesh shaders) when no `FSSM`-magic sidecar is present (FSPX programs or synthetic listings). Confirmed across all 26,503 corpus blobs with 0 contradictions against GFX10 SOP1/SOP2/SOPC/VOP3 encodings: 23,841 wave64 (1,154 CS, 195 GS, 9,282 MS, 10,974 PS, 2,236 VS) and 2,662 wave32 (1,535 CS, 1,127 PS); the code-marker heuristic alone misclassified 2,287 markerless wave64 shaders as wave32 (287 CS: 162 straight-line and 125 branchy, including 11 with `v_readlane_b32`, 35 `v_readfirstlane_b32`, 29 `ds_swizzle_b32`, 14 `s_barrier`; 943 PS: 906 straight-line and 37 branchy; 1,057 VS: 1,020 straight-line and 37 branchy); CPU-checked by `tests/test_fssm_header.py` and `tests/test_fssm_wave_size.py`. Until 2026-11-21 a mask-only wave64 program with no EXEC markers was translated as wave32, so `s_bcnt1_i32_b64` counted one half (#210). GPU-checked with `runtime/test/shaders/cs_w64_mask_detect.asm` (48 set bits of `(lane & 5) != 0`) on NVIDIA GeForce RTX 5060 under `LEONIDA_W64_EMULATE=1`. The hardware lane is exact in compute and mesh shaders (LocalInvocationIndex mod 64 or 32) and is used by `v_mbcnt` and EXEC writes. In other stages it's the subgroup lane. Constant EXEC writes (`s_mov_b32 exec_lo/exec_hi, K`) set each lane from its own bit of K, as `(K >> lane) & 1` (shift and mask: Intel's Windows driver evaluated `OpBitFieldUExtract` of a constant that fits in 16 bits with the lane taken mod 16, so `exec_lo = 0xffff` ran all 32 lanes; GPU-checked with `runtime/test/shaders/cs_exec_const.asm` on Intel UHD Graphics 770, driver 32.0.101.6129, and NVIDIA GeForce RTX 4080 SUPER); before, any non-zero constant turned every lane on. A register written to `exec_hi` sets lanes 32–63 only. VCC's halves follow the same rule while VCC holds a lane mask: a 32-bit write to `vcc_lo` sets lanes 0–31 of the mask and one to `vcc_hi` lanes 32–63 (until 2026-11-22 a `vcc_lo` write set all 64 lanes and a `vcc_hi` write never reached the mask that `s_cbranch_vccz`/`v_cndmask` read; CPU-checked by `tests/semantic/test_wave64_vcc_half_write.py`, not GPU-checked). Mask and `0`/`-1` half-writes to `vcc_lo`/`vcc_hi` keep VCC tracked as a lane mask across subsequent ops (`s_bcnt1_i32_b64`, further half-writes), whereas plain-data writes (`s_buffer_load_dword vcc_lo`, `s_load_dword`, scalar ALU, non-mask constants) end VCC's mask state and store the scalar word across all 64 lanes instead of updating only one mask half (confirmed on 1 wave64 PS in the 1.0.2.1 corpus and `tests/semantic/test_wave64_vcc_half_write.py`). GPU-checked with `runtime/test/shaders/cs_exec64.asm`: lanes 16–47 enabled from two constants, exact on a 32-wide-subgroup GPU. Still approximate on 32-wide subgroups: cross-lane ops between the two halves of a wave64 (readlane/permlane/DPP/shuffles across lane 31/32, wave-wide reductions). The metadata index marks every wave64 shader so a runtime can request `requiredSubgroupSize = 64` where supported (AMD), which makes those exact too. | | Lane select (`v_readlane_b32` / `v_writelane_b32`) | The lane is **S1[4:0] in wave32** and S1[5:0] in wave64, from an SGPR or a constant, and EXEC is ignored (RDNA 3 ISA guide pseudocode for both opcodes; RDNA 2 has the same encoding and gives no pseudocode). **Until #488 (SHADER-52) a wave32 shader masked with 63 as well**: a lane select of 32 or more wrote no lane, and a read shuffled from a lane past the end of a 32-wide subgroup, which SPIR-V leaves undefined (NVIDIA wraps it, so reads happened to come out right there). Found by the FUZZ-7 cross-lane fuzzer: 23 of 100 random wave32 programs, each minimized to `s_mov_b32 s28, K; v_writelane_b32 vD, x, s28` with K ≥ 32. GPU-checked with `runtime/test/shaders/cs_w32_lane_wrap.asm` (25 16 777 777) on NVIDIA GeForce RTX 5060 (#488) and RTX 4090 (subgroup 32, driver 621.14); `tests/test_translate.py` checks the masks in the SPIR-V, and `tests/semantic/test_wave32_lane_select.py` runs the shader across 32 lanes, where a mask of 63 is an out-of-range shuffle. | -| First active lane in a vertex shader (`v_readfirstlane_b32`, MoltenVK) | A native `v_readfirstlane_b32` is a ballot of the EXEC lanes, its lowest set bit, and a shuffle from that lane (lane 0 when no lane is on). **In a vertex shader the lowest bit is taken with `FindILsb` over the ballot's four words** (the lowest non-zero word wins), not with `OpGroupNonUniformBallotFindLSB`. The two give the same lane, because a ballot has no bit at or above the subgroup size. Other stages keep `BallotFindLSB`; the `--wave64-emulate` form already used `FindILsb` on its two mask words. Why: MoltenVK lowers `BallotFindLSB`, like the `SubgroupSize` built-in, to Metal's `threads_per_simdgroup` input, which a vertex function can't declare ("invalid 'threads_per_simdgroup' attribute for input declaration in a vertex function"), so every VS with a readfirstlane failed to compile there. **Confirmed on an Apple M4 (MoltenVK 1.4.2):** hand-written VS with `subgroupBallotFindLSB` or `gl_SubgroupSize` fail, and ballot, shuffle, broadcast-first, elect, votes, and ballot + `findLSB` + shuffle (32- and 64-lane forms) create. Corpus (1.0.2.1, translated from `4eb6155d`): 572 of the 2,236 VS contain `v_readfirstlane_b32`, and exactly those 572 modules change; all 2,236 stay `spirv-val`-valid. VS pipelines on the M4 go from 667 to 672 of 2,236 on main (the rest fail on the subgroup lane built-in, #1784), and from 1,662 to 2,233 with #1784's vertex-subgroup workaround (its flag is not on main) (the 571 `threads_per_simdgroup` failures are gone). `tests/semantic/test_vs_readfirstlane.py` runs it on the wave interpreter with the first EXEC lane in word 0 and word 1. | +| First active lane in a vertex shader (`v_readfirstlane_b32`, MoltenVK) | A native `v_readfirstlane_b32` is a ballot of the EXEC lanes, its lowest set bit, and a shuffle from that lane (lane 0 when no lane is on). **In a vertex shader the lowest bit is taken with `FindILsb` over the ballot's four words** (the lowest non-zero word wins), not with `OpGroupNonUniformBallotFindLSB`. The two give the same lane, because a ballot has no bit at or above the subgroup size. Other stages keep `BallotFindLSB`; the `--wave64-emulate` form already used `FindILsb` on its two mask words. Why: MoltenVK lowers `BallotFindLSB`, like the `SubgroupSize` built-in, to Metal's `threads_per_simdgroup` input, which a vertex function can't declare ("invalid 'threads_per_simdgroup' attribute for input declaration in a vertex function"), so every VS with a readfirstlane failed to compile there. **Confirmed on an Apple M4 (MoltenVK 1.4.2):** hand-written VS with `subgroupBallotFindLSB` or `gl_SubgroupSize` fail, and ballot, shuffle, broadcast-first, elect, votes, and ballot + `findLSB` + shuffle (32- and 64-lane forms) create. Corpus (1.0.2.1, translated from `4eb6155d`): 572 of the 2,236 VS contain `v_readfirstlane_b32`, and exactly those 572 modules change; all 2,236 stay `spirv-val`-valid. VS pipelines on the M4 go from 667 to 672 of 2,236 on main (the rest fail on the subgroup lane built-in, #1784), and from 1,662 to 2,233 with #1784's vertex-subgroup workaround (its flag is not on main) (the 571 `threads_per_simdgroup` failures are gone). `tests/semantic/test_vs_readfirstlane.py` runs it on the wave interpreter with the first EXEC lane in word 0 and word 1. A wave32 VS translated with halves (row "Wave32 vertex shaders on wider subgroups") takes `FindILsb` of its own wave's word instead, ballot word `SubgroupLocalInvocationId / 32`, still without `BallotFindLSB`; on MoltenVK `make_game.py` passes `--no-wave32-halves`, so the four-word form above is what runs there. | | Wave64 emulation (`--wave64-emulate`) | Wave64 compute and mesh shaders exact on **any** subgroup size (32-wide NVIDIA, Intel, AMD in wave32 mode), with no subgroup operation at all. One invocation is still one lane. Everything a lane needs from the rest of its wave goes through a Workgroup buffer `%x_buf`: votes (`s_cbranch_vccz/vccnz/execz/execnz`, SCC of mask ops, `s_cmp` of masks), whole-mask words (`s_bcnt1`, `s_ff1`, `v_mbcnt`), `v_readlane`, `v_readfirstlane`, `ds_bpermute`, `ds_swizzle`, `v_permlane16/x16`. The program runs in rounds: in each round every wave that is neither done nor waiting at `s_barrier` runs one segment of its program (a basic block, cut at each cross-lane op), then the whole workgroup meets at one `OpControlBarrier` (Workgroup, AcquireRelease, workgroup + uniform + image memory) that sits in uniform control flow, because every invocation runs every round. A cross-lane op ends its segment after the lane has stored its value (per-lane data, double-buffered by round parity) or ORed its bit (two mask words per wave, three slots by round mod 3, each slot cleared two rounds after it was read); the code after it runs one round later, when all 64 lanes have written. SSA values live across a cut go through Function variables. `s_barrier` is a scheduler state: the wave stops running segments until every wave that isn't done is waiting, which is also how hardware counts finished waves. A memory access that conflicts with an earlier one in the same segment (read after write, write after read, write after write; LDS and buffer/image memory separately) starts a new round, so two halves of a wave in different subgroups access memory in instruction order, as the lanes of one hardware wave do. A scalar load (`s_load*`, `s_buffer_load*`) counts as a buffer read: until #1587 it was left out, so a store and a later scalar load of the same address shared a segment and the half in the other subgroup could load before this half had stored (`valu_fuzz.py --family mem --emulate`: lanes 32-63 read the fill pattern after an `s_buffer_load`/`s_load` of the slot lane 0 had written, on RDNA1 RADV and an RTX 5060; `v_readfirstlane_b32`, which gives that slot, already reads the whole wave). Pinned by `tests/semantic/test_w64x_scalar_load_order.py` (no segment of the emitted rounds accesses buffer memory after a write or writes after a read; three of its five cases fail without the rule). Confirmed by that CPU test and the ordering argument above; the race does not show on an RX 7900 XTX (AMD 26.10.1 LLPC, Windows 11): `valu_fuzz.py --family mem --seed 5 --programs 21 --wave 64 --emulate` matches 21/21 before and after the rule (3 runs each), so a GPU reproduction on RDNA1/RADV (where #1587 was found) is still pending. Not ordered: sampling an image the wave wrote. The missing lanes of a partial last wave read as 0. Without the flag the output is unchanged, apart from two fixes that apply to every wave64 compute/mesh shader: `v_writelane_b32` selects the lane by the wave lane (on a 32-wide subgroup writes to lanes 32–63 were lost; `cs_w64x_writelane`), and `ds_bpermute_b32` (see the LDS row). Fewer rounds, same results: a whole-mask read (`s_bcnt1`, `v_mbcnt_lo/hi`, ...) of the value of the same register (or EXEC) that an earlier read in the block already exchanged reuses that exchange (the value's identity is the SSA id last stored to the register, forgotten at block start and at any label); and a block that ends in a voted branch (`s_cbranch_vccz/vccnz/execz/execnz`) runs its successor in the round that reads the vote, since that segment only reads the vote and picks the next block (an inner loop in the scheduler, flag `%x_chain`). Both rules are pinned by `cs_w64x_mask_reuse` (a mask register and EXEC rewritten between reads), `cs_w64x_mask_reuse2` (EXEC read twice, a read after a buffer store, one half of a mask pair rewritten while the other is kept, a voted branch whose successor starts with a load of the other half's earlier store) and `cs_w64x_chain_barrier` (a voted branch whose successor starts with `s_barrier`, two waves): expected values from the ISA, first run on the AMD 880M with its native 64-wide subgroup, then emulated on both GPUs; `tests/test_translate.py` counts the exchanges in the SPIR-V (one per value, a new one after a rewrite of the register or EXEC), and the translator refuses (`Unsupported`) a voted branch whose segment was not started by the vote's own round. Under `--wave64-emulate`, `tools/wave64_emulate_opt.py` runs three exact CFG/dataflow passes to eliminate redundant scheduler rounds and global `OpSwitch` blow-up (#884): (1) backward `SCC` liveness skips `scc_from_mask` / `scc_any_half` votes on lane-mask ops (`s_*_saveexec_*`, `s_andn1/andn2_wrexec_*`, `s_and/or/xor/andn2/orn2/nand/nor/xnor/not_b64`, `s_wqm_*`) whenever `SCC` is dead-out (never read before an unconditional overwrite or `s_endpgm`), (2) safe lane-local `s_cbranch_execz`/`execnz` region folding inlines single-entry, single-exit post-dominated regions with no cross-lane ops, no `s_barrier`, no unmasked side effects, no `write_all_lanes` mask spills, no `EXEC`-widening, no live-out scalars, and for each memory domain (`mem`/`lds`) either read-only accesses or an acyclic single write/atomic behind `if (%active)` (issuing any uniform `x_memory_order` split/barrier before the branch — including scalar `s_load*`/`s_buffer_load*` per #1587 — and chaining single-predecessor continuations), and (3) structured emulation (`plan_structured_emulation`, `control_flow = "emulated wave64 structured"`) removes the global round-loop `OpSwitch` on multi-superblock reducible CFGs without non-uniform 32-bit half-mask SCC: single-wave workgroups (`<= 64` threads) run 100% inline structured SPIR-V with direct workgroup barriers (`0` `OpSwitch`, `0` `x_spill`, strictly monotone GEN/KILL 4-bit `dirty_in` memory ordering across blocks and loop back-edges), while multi-wave workgroups (`> 64` threads, without divergent `s_barrier`) emit post-dominating spine blocks and barrier-free guards/loops (including live-out scalars, single-write stores, `EXEC`-widening, and read-only loops) inline and isolate any remaining wave-divergent barrier regions into local mini-schedulers (or a tail scheduler at early `s_endpgm`). Checked on the CPU by `tests/semantic/test_wave64_emulate_opt.py` (40/64/128/256-thread workgroup interpreter with strict uniform barrier checks, ScreenProbes-shaped chains, nested/reused `saveexec` folds, single-store WAR/RAW ordering, single-wave `inline_all` loop-carried WAR, monotone `dirty_in` regression after `x_round`, multi-wave `structured_hybrid` + local `mini_scheduler`, divergent `s_barrier` fallback, `cs_w64x_saveexec_b64.s` fixture, and negative controls; **not yet GPU-verified** for the structured emulation pass). (1) backward `SCC` liveness skips `scc_from_mask` / `scc_any_half` votes on lane-mask ops (`s_*_saveexec_*`, `s_andn1/andn2_wrexec_*`, `s_and/or/xor/andn2/orn2/nand/nor/xnor/not_b64`, `s_wqm_*`) whenever `SCC` is dead-out (never read before an unconditional overwrite or `s_endpgm`), and (2) safe lane-local `s_cbranch_execz`/`execnz` region folding inlines single-entry, single-exit post-dominated regions with no cross-lane ops, no `s_barrier`, no memory/LDS writes, no unmasked side effects, no `write_all_lanes` mask spills, no `EXEC`-widening, and no live-out scalars behind `if (%active)` (issuing any uniform `x_memory_order` split before the branch — including scalar `s_load*`/`s_buffer_load*` per #1587 — and chaining single-predecessor continuations), keeping all 64 lanes of each wave in the same scheduler round. Checked on the CPU by `tests/semantic/test_wave64_emulate_opt.py` (64-thread and 128-thread workgroup interpreter with uniform barrier checks, ScreenProbes-shaped chains, nested/reused `saveexec` folds, internal loop, `cs_w64x_saveexec_b64.s` fixture, RAW memory/scalar-load ordering, and negative controls for live-out scalars, stores, cross-lane ops, and EXEC-widening). `scripts/bench_wave64.py` times `cs_bench_mix` native and emulated and checks the emulated output bytes against the native AMD run. Cost: one workgroup barrier per segment, and `%x_buf` = (2·L + 6·W + 7) dwords for L invocations in W waves, counted in `lds_bytes`. GPU-checked on NVIDIA GeForce RTX 5070 Laptop (subgroup 32, driver 617.42) and AMD Radeon 880M (subgroup 64, AMD driver 26.11.2 LLPC): `check.py` 38/39 (the mesh test runs in the other script) and `scripts/run_gpu_tests.py` 40/40 on both with `LEONIDA_W64_EMULATE=1`, including every wave64 test (`cs_wavemask`, `cs_wave64_ballot`, `cs_wm_*`) and the cross-half suite `cs_w64x_*` / `ms_w64x_ballot`: readlane and writelane at lanes ≥ 32, readfirstlane with only upper lanes active, branches voted by one lane of either half, ballot + `v_mbcnt_lo/hi` compaction over 64 lanes (also in a mesh shader, 4096/4096 pixels), a 128-thread workgroup whose two waves take different branches, `s_barrier` between waves with different loop counts, LDS read-after-write and write-after-read across the halves without a barrier, a load, ballot and load in one block, and a partial wave (group 40). Without the flag the same RTX 5070 passes 19/37 (the wave64 tests skip there). Not covered: VS/PS/GS (no workgroup memory or barrier there). Known driver bug: AMD's Windows shader compiler for RDNA2 crashes (access violation in `vkCreateComputePipelines`) on many emulated compute shaders with LDS (#857: drivers 32.0.21030 to 32.0.21045.29003, iGPUs and RX 6000; 23.20.44, RDNA3, RDNA4, RADV and NVIDIA are fine), so `make_game.py --wave64-emulate auto` leaves emulation off when the runtime's GPU is such a device and runs wave64 natively (`rdna2_amd_windows` in `tools/vk_subgroup_info.py`, by PCI device ID and driver ID). | | Workgroup memory limit (SHADER-309) | A compute shader's Workgroup variables, the LDS array plus `%x_buf` (the wave64 exchange, 2·L + 6·W + 7 dwords, or the 3 barrier-round counts), must fit in the device's `maxComputeSharedMemorySize`. `spirv-val` does not check device limits, and RADV (Mesa 27.0.0-devel, RX 7600) dies with SIGFPE in `vkCreateComputePipelines` on a module 4 bytes over 64 KiB (#1721, hand-built repro by YaBulochka). The limit differs per device: 65536 on RADV and NVIDIA, 32768 on the AMD Windows driver (RX 9070 XT, 32.0.32029.2010) and Intel (UHD 770, 101.7092), measured by towade in #1745; the Vulkan minimum is 16384. The translator runs offline, so it has two parts. (1) `rdna2spirv.py` keeps every module under a hard cap, `MAX_SHARED_BYTES` (`--max-shared-memory`, default 65536): the LDS array is the program's need (RSRC2 LDS_SIZE, or the end of the furthest constant-offset access, counted exactly from the offset and the access width: a b32 at offset 65,532 ends at 16,384 dwords) rounded up to a power of two; when that plus `%x_buf` is over the cap but the need still fits, the array shrinks to the RSRC2 allocation and its accesses are bounds-checked (below); when the need itself does not fit (a 64 KiB LDS under `--wave64-emulate`) the shader is refused (`Unsupported`, with the byte counts). The array is clipped to 16,384 dwords, but an RSRC2 allocation over the cap (LDS_SIZE above 128 units, so 66,048 B or more) is counted at its full size and refused, native or emulated, instead of being cut. LDS bounds: RDNA2 LDS does not wrap, and an access outside the workgroup's allocation reads 0 and its write is dropped (RDNA2 ISA sections 3.6.1 and 3.6.6). The wrapped power-of-two array aliases such an access onto a valid word, so when a program's constant offsets reach past its RSRC2 allocation, or the array was shrunk, the array is the allocation and `Gen.lds_access` checks every dword (`index < allocation`, else a read or an atomic's old value is 0 and the write or atomic is skipped): `ds_read*`/`ds_write*` of every width (b64/b96/b128 and read2/write2 per dword), the sub-dword reads and writes, every LDS atomic, `ds_cmpst`, `ds_mskor`, `ds_wrxchg*`. `ds_swizzle`/`ds_bpermute`/`ds_permute` do not use `%lds`; `ds_append`/`ds_consume` were already refused. Every other shader keeps the wrapped array and emits no check, as before. Hypothesis, not yet counted over the corpus: the 16 of 486 LDS-using CS that index past LDS_SIZE with constant offsets (the Compute shaders row) now read 0 there, as the ISA says, where they used to read the wrapped word. Counted over a 1.0.2.1 corpus by towade (#1882, counts only): with the exact need (offset + access width) none of the 485 LDS-using CS reaches past its RSRC2 allocation with a constant offset, so none gets a bounds check (no `OpULessThan` added, native or emulated); the "16 of 486" in the Compute shaders row came from the older offset + 4-dword estimate. `%x_buf` is already sized to the workgroup's waves, so it has nothing to give back. `lds_bytes` in `index.json` is the module's whole Workgroup total (LDS, `%x_buf`, a mesh shader's `%ms_counts`). (2) The D3D12 shim's `create_compute` compares `lds_bytes` with the device's `maxComputeSharedMemorySize` and refuses the pipeline with a log line (`E_NOTIMPL`) instead of creating an invalid one. Pinned by `tests/semantic/test_cs_shared_memory_limit.py` (Workgroup bytes counted from the emitted SPIR-V: under the cap unchanged, shrunk to the 51,200 B allocation and bounds-checked, the exact-cap boundary, an access ending at 64 KiB counted exactly, a 64 KiB LDS refused when emulated and accepted natively, a native 66,048 B allocation refused, run through `spirv_mini_interp`: an out-of-range write dropped with the word it would wrap to intact, out-of-range reads (b32, u16) giving 0, a b64 write straddling the allocation's end, out-of-range atomics returning 0 and changing nothing, and an in-range shader with no check; `lds_bytes` equal to the SPIR-V total) and `shader_library_test` (`lds_bytes` read from the index). Confirmed by those CPU tests only; GPU runs (RADV; AMD Windows and Intel at 32 KiB) are pending. Not covered: mesh shaders against `maxMeshSharedMemorySize`. | | Barycentric fallback (`--bary-fallback`) | For devices without `VK_KHR_fragment_shader_barycentric` (NVIDIA Pascal, for one). The raw pair a PS reads ("PS system inputs": 321 PS) comes from an ordinary vec3 input, `%bary`, at the lowest location none of the shader's attributes uses, instead of `BuiltIn BaryCoordKHR`. The module then needs neither the `FragmentBarycentricKHR` capability nor the extension, and the index records the location as `bary_fallback_input`. The stage before the PS writes (1,0,0), (0,1,0), (0,0,1) at the triangle's three vertices: `tools/bary_fallback_gs.py` writes that pass-through geometry shader from the index (Position and the PS's input locations copied unchanged). Default (perspective) interpolation of those weights is the perspective-correct barycentric, the value `BaryCoordKHR` has, so `.y`/`.z` stay AMD's i/j; shaders that don't read the pair translate to the same module either way. GPU-checked on an NVIDIA GeForce GTX 1060 6GB (Pascal, no barycentric extension; driver 560.94, Windows 10) with `LEONIDA_BARY_FALLBACK=1`: `ps_bary` 4096/4096 pixels exact, and `ps_uniform_branch` and `ps_scc_mask32` pass, through `run_gpu_tests.py` and `build.py` + `check.py`, with zero Khronos validation messages. Checked in `tests/semantic/test_bary_fallback.py`. For a known VS/PS pair, `python -I tools/bary_fallback_gs.py DIR --pair VS PS` builds `PS.bary_gs.clipN.spv`. It copies the producer’s `ClipDistance[N]` at each emitted vertex, using the VS index field `clip_distance_count`. On RTX 5080 and Radeon integrated graphics, two independently shifted clip planes yielded 512, 1024, 2048 or 4096 covered pixels, matching the native barycentric path. For a cull-only VS the pair writes `PS.bary_gs.cullN.spv` from `cull_distance_count`. A two-plane synthetic draw on the same GPUs covered 0 pixels when every vertex was negative for either plane and all 4096 when each plane had a nonnegative vertex. The helper rejects mixed clip/cull arrays. The runtime building that GS per pipeline is the follow-up (it needs the graphics pipelines of #291). | diff --git a/make_game.py b/make_game.py index cb12b78c67..8aec70163f 100644 --- a/make_game.py +++ b/make_game.py @@ -1127,7 +1127,8 @@ def fspx_key_clash(spirv: str): # The translator's fallback flags make_game.py can forward, and the argparse attribute each one reads. FALLBACK_FLAGS = (("--no-float-controls", "no_float_controls"), ("--bary-fallback", "bary_fallback"), ("--texel-offset-fallback", "texel_offset_fallback"), ("--mesh-compute", "mesh_compute"), - ("--f16-interp-fallback", "f16_interp_fallback"), ("--pc-tail-ubo", "pc_tail_ubo")) + ("--f16-interp-fallback", "f16_interp_fallback"), ("--pc-tail-ubo", "pc_tail_ubo"), + ("--no-wave32-halves", "no_wave32_halves")) def fallback_flags(a) -> tuple[str, ...]: @@ -1232,6 +1233,18 @@ def runtime_gpu_per_vertex(): return None +VK_DRIVER_ID_MOLTENVK = 14 + + +def wave32_halves_fallback(info: dict) -> str | None: + """Reason to use the old VS lowering on the selected GPU, if known.""" + if info.get("driver_id") == VK_DRIVER_ID_MOLTENVK: + return "MoltenVK vertex functions cannot read the subgroup lane" + if info.get("vertex_ballot") is False: + return "the device does not support subgroup ballots in vertex shaders" + return None + + def runtime_gpu_max_push_constants(): """max_push_constants_size as tools/vk_subgroup_info.py answers for the GPU the runtime would use, or None.""" v = runtime_gpu_info().get("max_push_constants_size") @@ -1839,6 +1852,9 @@ def main() -> int: ap.add_argument("--mesh-compute", action="store_true", help="translate mesh shaders to compute shaders writing an output buffer, for devices " "without VK_EXT_mesh_shader") + ap.add_argument("--no-wave32-halves", action="store_true", + help="translate wave32 vertex shaders as one wave per subgroup instead of one per 32 subgroup " + "lanes; selected automatically on MoltenVK and devices without vertex subgroup ballots") ap.add_argument("--pc-tail-ubo", action="store_true", help="keep s0..s31 in 128 push-constant bytes and move heap/code base to a set-1 uniform " "block; on by itself when the runtime's GPU reports maxPushConstantsSize below what " @@ -1915,6 +1931,11 @@ def main() -> int: log("shaders: the GPU the runtime would use can't take PerVertexKHR inputs (MoltenVK, or no " "fragmentShaderBarycentric): translating with --f16-interp-fallback") a.f16_interp_fallback = True + if "shaders" in stages and not a.no_wave32_halves: + reason = wave32_halves_fallback(runtime_gpu_info()) + if reason: + log(f"shaders: {reason}; translating with --no-wave32-halves") + a.no_wave32_halves = True if "shaders" in stages and not a.pc_tail_ubo: need_pc = 152 if a.mesh_compute else 144 max_pc = runtime_gpu_max_push_constants() diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h index 528fd013d6..bfacf8a833 100644 --- a/runtime/src/shader_library.h +++ b/runtime/src/shader_library.h @@ -637,6 +637,10 @@ struct ShaderEntry { // subgroup size. Empty for a native translation. std::string wave64_exchange; bool emulated() const { return !wave64_exchange.empty(); } + // A wave32 vertex shader translated with one wave per 32 subgroup lanes (rdna2spirv.py Gen.halves): exact on any + // subgroup size that is a multiple of 32, so a 64-wide vertex stage (the AMD Windows driver) runs it as two + // wave32s. False for one translated with --no-wave32-halves or before the field existed. + bool wave32_halves = false; std::vector input_signature; // vertex shaders: what the input layout must feed std::vector inputs; // pixel shaders: input locations declared std::vector outputs; // pixel/vertex shaders: output locations written @@ -788,6 +792,8 @@ class ShaderLibrary { e.subgroup_size = u32(g); if (const Json* x = meta.find("wave64_exchange"); x && x->kind == Json::Kind::string) e.wave64_exchange = x->string; + if (const Json* h = meta.find("wave32_halves"); h && h->kind == Json::Kind::boolean) + e.wave32_halves = h->boolean; if (const Json* s = meta.find("input_signature"); s && s->kind == Json::Kind::array) { for (const Json& item : s->array) { SignatureElement element; diff --git a/runtime/src/subgroup_size.h b/runtime/src/subgroup_size.h index c391b7e63d..bd38f2bd15 100644 --- a/runtime/src/subgroup_size.h +++ b/runtime/src/subgroup_size.h @@ -67,6 +67,8 @@ enum class SubgroupOutcome { device_fixed, // the device has one size and it is the wanted one: nothing to ask for device_default, // cannot be required, but the default size is the wanted one: works, not guaranteed stable unavailable, // the wanted size cannot be had: the shader runs at another size and may be inexact + halves, // wave32 with `wave32_halves`: the size cannot be had, but every size the device runs is a + // multiple of 32 and the shader keeps each wave in its own 32 lanes unknown_stage, // no Vulkan stage for this entry unknown_device, // the device sizes were not queried (all zero): nothing is asked for }; @@ -103,6 +105,10 @@ inline bool subgroup_workgroup_fits(const std::array& local_si // - A device whose one and only subgroup size (min == max) is the wanted one needs nothing (`device_fixed`). // - Where the size cannot be required (stage not listed, feature off) but the device default is the wanted size, // the shader works as it is (`device_default`): nothing guarantees it, a driver may change its default. +// - A wave32 entry with `wave32_halves` (a vertex shader) partitions a wide subgroup into 32-lane waves, so where neither +// holds but the device's smallest size (minSubgroupSize, else the default) is at least 32 the outcome is +// `halves`: no width to request. The tested RX 7600 Windows driver (vertex stage 64-wide, VERTEX not +// requirable) is that case. // Otherwise the outcome is `unavailable`. inline SubgroupRequest decide_subgroup_size(const ShaderEntry& entry, const SubgroupSizeCaps& caps) { SubgroupRequest r; @@ -136,6 +142,9 @@ inline SubgroupRequest decide_subgroup_size(const ShaderEntry& entry, const Subg r.flags |= VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT; } else if (caps.default_size == r.wanted) { r.outcome = SubgroupOutcome::device_default; + } else if (entry.wave32_halves && !entry.wave64 && r.wanted == 32 && + (caps.min_size ? caps.min_size : caps.default_size) >= 32) { + r.outcome = SubgroupOutcome::halves; } else { r.outcome = SubgroupOutcome::unavailable; } diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py index 330af9f4f3..7db5b3a496 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py @@ -29,6 +29,9 @@ from pathlib import Path HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) # this script is run with python -I too +import w32_vs_halves # noqa: E402 (the wave32 VS fixtures' invariant checks) +W32_VS_FIXTURES = w32_vs_halves.FIXTURES # vs_w32_*: judged against wave32 invariants, not fixed words EXE = ".exe" if os.name == "nt" else "" UNSUPPORTED = 77 # a test tool exits with this when the device lacks a feature @@ -1310,6 +1313,13 @@ def interp_f16_high_problem(px): return "" if err < 2e-3 else f"f16 halves off by {err:.3g}" +def w32_vs_halves_test(tools, spirv, name): + """A vs_w32_* fixture: a wave32 VS on a vertex subgroup that may be wider than 32 lanes, drawn with 960 vertices + and checked against what every wave32 satisfies, whatever packing the driver chose (w32_vs_halves.py).""" + problem = w32_vs_halves.check(tools, spirv, name) + return Skip(problem) if problem.startswith("SKIP") else problem + + def base_ids_test(tools, spirv): """vs_base_ids with ps_flat, drawn with firstVertex 16 and firstInstance 7: the VS input VGPRs are zero-based on the hardware, so every pixel must still see vertex 0 of instance 0 (0x101, 0x102), not 0x7111.""" @@ -1560,6 +1570,8 @@ def main(): for name in TEXTURE_CONSTANTS: results.append((name, texture_constant_test(tools, spirv, name))) results.append(("vs_base_ids", base_ids_test(tools, spirv))) + for name in W32_VS_FIXTURES: + results.append((name, w32_vs_halves_test(tools, spirv, name))) results.append(("ps_tex", bindless_test(tools, spirv))) results.append(("ps_ssharp", sampler_test(tools, spirv))) results.append(("ps_imgatomic", bindless_test(tools, spirv, "ps_imgatomic"))) diff --git a/runtime/test/shaders/vs_w32_ballot.asm b/runtime/test/shaders/vs_w32_ballot.asm new file mode 100644 index 0000000000..1b8b959ff3 --- /dev/null +++ b/runtime/test/shaders/vs_w32_ballot.asm @@ -0,0 +1,32 @@ +; Wave32 vertex shader on a 64-wide vertex subgroup (w32_vs_halves.py): a ballot read as a whole. VCC = the lanes +; whose vertex has v % 4 == 1 (v0 = vertex index). Record A at heap 0x1000 + 16 * v, record B at 0x5000 + 16 * v: +; A = (lane, rank, key, v) lane = v_mbcnt_lo of -1, rank = v_mbcnt_lo of VCC (selected lanes below this one, +; the slot a stream compaction would give), key = v_readfirstlane of v0 +; B = (count, first, sel, 0) count = s_bcnt1 of vcc_lo, first = s_ff1 of vcc_lo (the lowest selected lane, -1 if +; none), sel = v % 4 == 1 +; Checked per wave (the vertices with one key): count and first agree with the members' sel and lanes, and each +; member's rank is the number of selected members on lower lanes. +; Run: as vs_w32_lane.asm. +; mattr: +wavefrontsize32,-wavefrontsize64 +v_mbcnt_lo_u32_b32 v6, -1, 0 +v_and_b32_e32 v4, 3, v0 +v_cmp_eq_u32_e32 vcc_lo, 1, v4 +v_mbcnt_lo_u32_b32 v7, vcc_lo, 0 +v_readfirstlane_b32 s5, v0 +v_mov_b32_e32 v8, s5 +v_mov_b32_e32 v9, v0 +v_lshlrev_b32_e32 v12, 4, v0 +v_add_nc_u32_e32 v13, 0x1000, v12 +buffer_store_dwordx4 v[6:9], v13, s[0:3], 0 offen +s_bcnt1_i32_b32 s6, vcc_lo +s_ff1_i32_b32 s7, vcc_lo +v_mov_b32_e32 v6, s6 +v_mov_b32_e32 v7, s7 +v_cndmask_b32_e64 v8, 0, 1, vcc_lo +v_mov_b32_e32 v9, 0 +v_add_nc_u32_e32 v13, 0x5000, v12 +buffer_store_dwordx4 v[6:9], v13, s[0:3], 0 offen +v_mov_b32_e32 v5, 0 +exp pos0 v5, v5, v5, v5 done +exp param0 v5, v5, v5, v5 +s_endpgm diff --git a/runtime/test/shaders/vs_w32_lane.asm b/runtime/test/shaders/vs_w32_lane.asm new file mode 100644 index 0000000000..78ec27c5c0 --- /dev/null +++ b/runtime/test/shaders/vs_w32_lane.asm @@ -0,0 +1,24 @@ +; Wave32 vertex shader on a 64-wide vertex subgroup (w32_vs_halves.py): the wave's shape. Vertex v (v0 = vertex +; index) stores (lane, count, key, v) to its record at heap 0x1000 + 16 * v through the V# in s[0:3]: +; lane = v_mbcnt_lo_u32_b32 of -1: this vertex's lane in its wave, 0..31 in a wave32 +; count = s_bcnt1_i32_b32 of exec_lo: the wave's active lanes, at most 32 +; key = v_readfirstlane_b32 of v0: the vertex in the wave's first active lane, which names the wave +; Which vertices share a wave is the driver's choice, so the checks are what every wave32 must satisfy: the vertices +; with one key are one wave, there are `count` of them, at most 32, each on its own lane, and the first of them (the +; lowest lane) is the key's own vertex. +; Run: VKH_VERTICES=960 VKH_SGPRS=0,0,65536,0x30000000 VKH_HEAP=0=0 VKH_HEAP_DUMP=heap.raw vk_harness +; vs_w32_lane.spv out.raw (the triangles have zero area, so nothing is drawn). +; mattr: +wavefrontsize32,-wavefrontsize64 +v_mbcnt_lo_u32_b32 v6, -1, 0 +s_bcnt1_i32_b32 s4, exec_lo +v_mov_b32_e32 v7, s4 +v_readfirstlane_b32 s5, v0 +v_mov_b32_e32 v8, s5 +v_mov_b32_e32 v9, v0 +v_lshlrev_b32_e32 v12, 4, v0 +v_add_nc_u32_e32 v12, 0x1000, v12 +buffer_store_dwordx4 v[6:9], v12, s[0:3], 0 offen +v_mov_b32_e32 v5, 0 +exp pos0 v5, v5, v5, v5 done +exp param0 v5, v5, v5, v5 +s_endpgm diff --git a/runtime/test/shaders/vs_w32_shuffle.asm b/runtime/test/shaders/vs_w32_shuffle.asm new file mode 100644 index 0000000000..3ecd1decc3 --- /dev/null +++ b/runtime/test/shaders/vs_w32_shuffle.asm @@ -0,0 +1,36 @@ +; Wave32 vertex shader on a 64-wide vertex subgroup (w32_vs_halves.py): reads from other lanes of the wave. +; Record A at heap 0x1000 + 16 * v, record B at 0x5000 + 16 * v (v0 = vertex index): +; A = (lane, readlane5, key, v) readlane5 = v_readlane_b32 of v0 at lane 5, key = v_readfirstlane of v0 +; B = (xor1, next, readlane31, 0) xor1 = ds_bpermute_b32 of v0 from lane ^ 1, next = from (lane + 1) & 31 (each 0 +; when that lane is not in the wave), readlane31 = v_readlane_b32 of v0 at lane 31 +; Checked per wave (the vertices with one key): each value is the v of the member on that lane. +; Run: as vs_w32_lane.asm. +; mattr: +wavefrontsize32,-wavefrontsize64 +v_mbcnt_lo_u32_b32 v6, -1, 0 +v_readlane_b32 s6, v0, 5 +v_mov_b32_e32 v7, s6 +v_readfirstlane_b32 s5, v0 +v_mov_b32_e32 v8, s5 +v_mov_b32_e32 v9, v0 +v_lshlrev_b32_e32 v12, 4, v0 +v_add_nc_u32_e32 v13, 0x1000, v12 +buffer_store_dwordx4 v[6:9], v13, s[0:3], 0 offen +v_xor_b32_e32 v14, 1, v6 +v_lshlrev_b32_e32 v14, 2, v14 +v_add_nc_u32_e32 v15, 1, v6 +v_and_b32_e32 v15, 31, v15 +v_lshlrev_b32_e32 v15, 2, v15 +ds_bpermute_b32 v16, v14, v0 +ds_bpermute_b32 v17, v15, v0 +s_waitcnt lgkmcnt(0) +v_readlane_b32 s7, v0, 31 +v_mov_b32_e32 v6, v16 +v_mov_b32_e32 v7, v17 +v_mov_b32_e32 v8, s7 +v_mov_b32_e32 v9, 0 +v_add_nc_u32_e32 v13, 0x5000, v12 +buffer_store_dwordx4 v[6:9], v13, s[0:3], 0 offen +v_mov_b32_e32 v5, 0 +exp pos0 v5, v5, v5, v5 done +exp param0 v5, v5, v5, v5 +s_endpgm diff --git a/runtime/test/shaders/vs_w32_vote.asm b/runtime/test/shaders/vs_w32_vote.asm new file mode 100644 index 0000000000..d1b1465b1f --- /dev/null +++ b/runtime/test/shaders/vs_w32_vote.asm @@ -0,0 +1,34 @@ +; Wave32 vertex shader on a 64-wide vertex subgroup (w32_vs_halves.py): a wave-wide branch and a write to EXEC. +; (1) s_cbranch_vccz over a scalar write: only the wave that holds vertex 37 sets s5 = 7, every other wave keeps 0 +; (a wave-level culling decision has this shape). +; (2) exec_lo = 0xffff: lanes 0..15 of each wave write 1, lanes 16..31 keep 0, then EXEC is restored. +; Vertex v (v0 = vertex index) stores (lane, s5, key, v) to heap 0x1000 + 16 * v and (low16, 0, 0, 0) to 0x5000 + 16 * v, +; key = v_readfirstlane of v0. Checked per wave: s5 == 7 exactly in the wave that has vertex 37, low16 == lane < 16. +; Run: as vs_w32_lane.asm. +; mattr: +wavefrontsize32,-wavefrontsize64 +v_mbcnt_lo_u32_b32 v6, -1, 0 +s_mov_b32 s5, 0 +v_cmp_eq_u32_e32 vcc_lo, 37, v0 +s_cbranch_vccz 1 +s_mov_b32 s5, 7 +v_mov_b32_e32 v7, s5 +v_readfirstlane_b32 s6, v0 +v_mov_b32_e32 v8, s6 +v_mov_b32_e32 v9, v0 +v_lshlrev_b32_e32 v12, 4, v0 +v_add_nc_u32_e32 v13, 0x1000, v12 +buffer_store_dwordx4 v[6:9], v13, s[0:3], 0 offen +s_mov_b32 s10, exec_lo +v_mov_b32_e32 v6, 0 +s_mov_b32 exec_lo, 0xffff +v_mov_b32_e32 v6, 1 +s_mov_b32 exec_lo, s10 +v_mov_b32_e32 v7, 0 +v_mov_b32_e32 v8, 0 +v_mov_b32_e32 v9, 0 +v_add_nc_u32_e32 v13, 0x5000, v12 +buffer_store_dwordx4 v[6:9], v13, s[0:3], 0 offen +v_mov_b32_e32 v5, 0 +exp pos0 v5, v5, v5, v5 done +exp param0 v5, v5, v5, v5 +s_endpgm diff --git a/runtime/test/shaders/w32_vs_halves.py b/runtime/test/shaders/w32_vs_halves.py new file mode 100644 index 0000000000..403f9de0ef --- /dev/null +++ b/runtime/test/shaders/w32_vs_halves.py @@ -0,0 +1,245 @@ +"""Wave32 vertex shaders on a vertex subgroup wider than 32 lanes (the tested RX 7600 Windows driver runs the +vertex stage 64-wide and omits VERTEX from requiredSubgroupSizeStages). + + python3 -I runtime/test/shaders/w32_vs_halves.py [name ...] + +Each vs_w32_* fixture draws 960 zero-area vertices and stores two records of four words per vertex to the heap: A at +0x1000 + 16 * v and B at 0x5000 + 16 * v (v = vertex index). Which vertices share a wave is the driver's choice, so the +fixtures are checked against what every wave32 execution must satisfy, whatever the packing. The vertices that report +one key (v_readfirstlane of v0) are one wave. That wave must: + - have at most 32 vertices, each on its own lane 0..31 (v_mbcnt_lo of -1); + - have its key's vertex on its lowest lane; + - give every member the same wave-wide values (count, first lane, readlane, vote result); + - give each cross-lane value the member's value on the lane it names. + +A translation that runs a wave32 VS as one 64-lane wave breaks these: 64 vertices share a key, lanes 32..63 report +lane 32, the ballot counts both halves, and v_readlane / ds_bpermute read the wrong half. + +Exit 0 when every fixture meets its invariants, 1 when one does not, 77 when nothing could be drawn. With +LEONIDA_VK_VALIDATION=1 (or VKH_VALIDATION=1) the draws run under VK_LAYER_KHRONOS_validation, loaded through the +loader's VK_INSTANCE_LAYERS with synchronization validation on, and any "Validation Error" line fails the fixture +(an interface error, ps_flat behind vs_w32_lane, prints VUID-RuntimeSpirv-OpEntryPoint-08743 there). The fragment +shader is ps_clip_color, which reads no input; the triangles have zero area, so it never runs. +check.py and scripts/run_gpu_tests.py call check() for each fixture. +""" +import os +import struct +import subprocess +import sys +import tempfile +from collections import defaultdict +from pathlib import Path + +EXE = ".exe" if os.name == "nt" else "" +UNSUPPORTED = 77 +VERTICES = 960 +A_WORD, B_WORD = 0x1000 // 4, 0x5000 // 4 +ENV = {"VKH_SGPRS": "0,0,65536,0x30000000", "VKH_HEAP": "0=0", "VKH_VERTICES": str(VERTICES)} +FIXTURES = ("vs_w32_lane", "vs_w32_ballot", "vs_w32_shuffle", "vs_w32_vote") +PS = "ps_clip_color" + + +def draw(tools, spirv, name, tmp): + """(records A, records B, harness output) or (None, message, output).""" + env = dict(os.environ, **ENV) + heap, raw = Path(tmp) / f"{name}.heap", Path(tmp) / f"{name}.raw" + env["VKH_HEAP_DUMP"] = str(heap) + if "1" in (os.environ.get("LEONIDA_VK_VALIDATION"), os.environ.get("VKH_VALIDATION")): + env["VK_INSTANCE_LAYERS"] = "VK_LAYER_KHRONOS_validation" + env["VK_KHRONOS_VALIDATION_VALIDATE_SYNC"] = "true" + cmd = [os.path.join(tools, "vk_harness" + EXE), os.path.join(spirv, name + ".spv"), + os.path.join(spirv, PS + ".spv"), str(raw)] + r = subprocess.run(cmd, capture_output=True, text=True, env=env, timeout=120) + out = r.stdout + r.stderr + if r.returncode == UNSUPPORTED: + return None, "unsupported: " + (out.strip().splitlines() or ["?"])[-1], out + if r.returncode or not heap.is_file(): + return None, f"exit {r.returncode}: {' | '.join(out.strip().splitlines()[-3:])}", out + w = struct.unpack("<%dI" % (65536 // 4), heap.read_bytes()) + rec = lambda base: [tuple(w[base + 4 * v:base + 4 * v + 4]) for v in range(VERTICES)] + return rec(A_WORD), rec(B_WORD), out + + +def waves(a): + """key -> list of (lane, v) of the vertices that name that key.""" + g = defaultdict(list) + for v, (lane, _, key, vv) in enumerate(a): + g[key].append((lane, v)) + return g + + +def shape_problems(a): + """The wave32 shape every fixture's A record carries: (lane, *, key, v).""" + p = [] + bad_v = [v for v, r in enumerate(a) if r[3] != v] + if bad_v: + p.append(f"{len(bad_v)} records were not written (first vertex {bad_v[0]})") + return p + for key, members in sorted(waves(a).items()): + lanes = [lane for lane, _ in members] + if len(members) > 32: + p.append(f"wave {key}: {len(members)} vertices share it (a wave32 has at most 32)") + if any(lane > 31 for lane in lanes): + p.append(f"wave {key}: lane ids up to {max(lanes)} (a wave32 has lanes 0..31)") + if len(set(lanes)) != len(lanes): + p.append(f"wave {key}: {len(lanes) - len(set(lanes))} vertices repeat a lane") + if min(members)[1] != key: + p.append(f"wave {key}: its lowest lane holds vertex {min(members)[1]}, not the key's") + return p + + +def check_lane(a, b): + p = [] + for key, members in waves(a).items(): + counts = {a[v][1] for _, v in members} + if counts != {len(members)}: + p.append(f"wave {key}: s_bcnt1 of exec_lo gave {sorted(counts)}, the wave has {len(members)} vertices") + return p + + +def check_ballot(a, b): + p = [] + for key, members in waves(a).items(): + lane_of = {v: lane for lane, v in members} + sel = sorted(lane for lane, v in members if v % 4 == 1) + want_first = sel[0] if sel else 0xFFFFFFFF + for lane, v in members: + count, first, s, _ = b[v] + rank = a[v][1] + want_rank = sum(1 for l in sel if l < lane) + if s != int(v % 4 == 1): + p.append(f"vertex {v}: v_cndmask of its own VCC bit gave {s}") + if count != len(sel): + p.append(f"wave {key}: s_bcnt1 of vcc_lo gave {count}, the wave selects {len(sel)}") + break + if first != want_first: + p.append(f"wave {key}: s_ff1 of vcc_lo gave {first}, the lowest selected lane is {want_first}") + break + if rank != want_rank: + p.append(f"vertex {v} (lane {lane_of[v]}): v_mbcnt_lo of VCC gave {rank}, want {want_rank}") + break + return p + + +def check_shuffle(a, b): + p = [] + for key, members in waves(a).items(): + on = {lane: v for lane, v in members} + for lane, v in members: + r5, r31 = a[v][1], b[v][2] + xor1, nxt = b[v][0], b[v][1] + if 5 in on and r5 != on[5]: + p.append(f"wave {key}: v_readlane lane 5 gave {r5}, lane 5 holds vertex {on[5]}") + break + if 31 in on and r31 != on[31]: + p.append(f"wave {key}: v_readlane lane 31 gave {r31}, lane 31 holds vertex {on[31]}") + break + if xor1 != on.get(lane ^ 1, 0): + p.append(f"vertex {v} (lane {lane}): ds_bpermute from lane {lane ^ 1} gave {xor1}, " + f"want {on.get(lane ^ 1, 0)}") + break + if nxt != on.get((lane + 1) & 31, 0): + p.append(f"vertex {v} (lane {lane}): ds_bpermute from lane {(lane + 1) & 31} gave {nxt}, " + f"want {on.get((lane + 1) & 31, 0)}") + break + return p + + +def check_vote(a, b): + p = [] + for key, members in waves(a).items(): + has37 = any(v == 37 for _, v in members) + for lane, v in members: + if a[v][1] != (7 if has37 else 0): + p.append(f"wave {key}: s5 = {a[v][1]} after s_cbranch_vccz, want {7 if has37 else 0} " + f"(the wave {'has' if has37 else 'does not have'} vertex 37)") + break + for lane, v in members: + if b[v][0] != int(lane < 16): + p.append(f"vertex {v} (lane {lane}): wrote {b[v][0]} under exec_lo = 0xffff, want {int(lane < 16)}") + break + return p + + +CHECKS = {"vs_w32_lane": check_lane, "vs_w32_ballot": check_ballot, "vs_w32_shuffle": check_shuffle, + "vs_w32_vote": check_vote} + +# What each problem line is about, for the per-category counts (the first pattern a line contains). +CATEGORIES = (("vertices share it", "wave > 32 vertices"), ("lane ids up to", "lane id > 31"), + ("repeat a lane", "repeated lane"), ("lowest lane holds", "readfirstlane not the first lane"), + ("of exec_lo", "s_bcnt1 exec_lo"), ("s_bcnt1 of vcc_lo", "s_bcnt1 vcc_lo"), ("s_ff1", "s_ff1 vcc_lo"), + ("v_mbcnt_lo of VCC", "v_mbcnt_lo rank"), ("own VCC bit", "per-lane VCC bit"), + ("readlane lane 5", "v_readlane 5"), ("readlane lane 31", "v_readlane 31"), + ("ds_bpermute from lane", "ds_bpermute"), ("s_cbranch_vccz", "vccz vote"), + ("exec_lo = 0xffff", "exec_lo write"), ("validation errors", "validation"), + ("not written", "records missing")) + + +def category(line): + return next((name for pat, name in CATEGORIES if pat in line), "other") + + +def evaluate(name, a, b, out): + """Every problem of one draw: the wave shape, the fixture's own checks, validation errors.""" + problems = shape_problems(a) + if not problems or not problems[0].endswith("not written (first vertex 0)"): + problems += CHECKS[name](a, b) + errors = [ln for ln in out.splitlines() if "Validation Error" in ln] + if errors: + problems.append(f"{len(errors)} validation errors, first: {errors[0][:200]}") + return problems + + +def check(tools, spirv, name): + """'' when `name` meets every wave32 invariant on this device, 'SKIP (...)' when it can't be drawn, else what is + wrong (for check.py and scripts/run_gpu_tests.py).""" + for n in (name, PS): + if not os.path.isfile(os.path.join(spirv, n + ".spv")): + return f"missing {n}.spv" + with tempfile.TemporaryDirectory(prefix="leonida-w32vs-") as tmp: + a, b, out = draw(tools, spirv, name, tmp) + if a is None: + return f"SKIP ({b})" if b.startswith("unsupported") else b + problems = evaluate(name, a, b, out) + return f"{len(problems)} problems, first: {problems[0]}" if problems else "" + + +def main(argv): + if len(argv) < 3: + print(__doc__) + return 2 + tools, spirv = argv[1], argv[2] + names = argv[3:] or list(FIXTURES) + failed = drawn = 0 + with tempfile.TemporaryDirectory(prefix="leonida-w32vs-") as tmp: + for name in names: + a, b, out = draw(tools, spirv, name, tmp) + if a is None: + print(f"{name}: {'SKIP' if b.startswith('unsupported') else 'FAIL'} ({b})") + failed += not b.startswith("unsupported") + continue + drawn += 1 + n_wave = len(waves(a)) + sizes = sorted({len(m) for m in waves(a).values()}) + problems = evaluate(name, a, b, out) + status = "FAIL" if problems else "ok" + print(f"{name}: {status}: {n_wave} waves, sizes {sizes[0]}..{sizes[-1]}, " + f"largest lane {max(r[0] for r in a)}, {len(problems)} problems") + if problems: + counts = defaultdict(int) + for line in problems: + counts[category(line)] += 1 + print(" by kind: " + ", ".join(f"{k} {n}" for k, n in sorted(counts.items()))) + firsts = {} + for line in problems: + firsts.setdefault(category(line), line) + for line in firsts.values(): + print(f" {line}") + failed += bool(problems) + if not drawn and not failed: + return UNSUPPORTED + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/runtime/test/subgroup_size_test.cpp b/runtime/test/subgroup_size_test.cpp index b7319e944d..7d513a59c8 100644 --- a/runtime/test/subgroup_size_test.cpp +++ b/runtime/test/subgroup_size_test.cpp @@ -5,6 +5,7 @@ // stages FRAGMENT | COMPUTE | TASK | MESH can be required; // - NVIDIA: every stage can be required, but the only size is 32; // - an old RADV: sizes 32..64, COMPUTE only. +// Plus a wave32 vertex shader translated with wave32_halves on each, and a device with sizes below 32. // No game data. #include "../src/subgroup_size.h" @@ -110,6 +111,17 @@ int main() { // A wave32 VS on a 64-wide default is wrong too. r = decide_subgroup_size(entry("vs", false), caps); CHECK(r.outcome == SubgroupOutcome::unavailable && r.wanted == 32); + // Unless it keeps each wave in its own 32 lanes (wave32_halves): exact at 64, nothing to chain or report. + ShaderEntry halves = entry("vs", false); + halves.wave32_halves = true; + r = decide_subgroup_size(halves, caps); + CHECK(r.outcome == SubgroupOutcome::halves && r.size == 0 && r.flags == 0 && r.wanted == 32 && + r.stage == VK_SHADER_STAGE_VERTEX_BIT); + // A stage that can be required still is: a halves pixel shader (not emitted today) would get 32. + ShaderEntry halves_ps = entry("ps", false); + halves_ps.wave32_halves = true; + r = decide_subgroup_size(halves_ps, caps); + CHECK(r.outcome == SubgroupOutcome::required && r.size == 32); // Emulated shaders ask for nothing, whatever the stage. r = decide_subgroup_size(entry("cs", true, {64, 1, 1}, true), caps); CHECK(r.outcome == SubgroupOutcome::emulated && r.size == 0 && r.flags == 0); @@ -125,6 +137,10 @@ int main() { const auto r = decide_subgroup_size(entry(stage, false), caps); CHECK(r.outcome == SubgroupOutcome::device_fixed && r.size == 0 && r.flags == 0); } + // A halves VS is the same there: the device's one size is 32. + ShaderEntry halves = entry("vs", false); + halves.wave32_halves = true; + CHECK(decide_subgroup_size(halves, caps).outcome == SubgroupOutcome::device_fixed); // Wave64 cannot be had (64 > max): native wave64 is reported in every stage, emulated is fine. for (const char* stage : {"cs", "ps", "vs", "gs", "ms"}) { const auto r = decide_subgroup_size(entry(stage, true), caps); @@ -148,6 +164,29 @@ int main() { CHECK(r.outcome == SubgroupOutcome::device_default && r.size == 0); r = decide_subgroup_size(entry("ms", true, {128, 1, 1}), caps); CHECK(r.outcome == SubgroupOutcome::device_default); + // A halves VS on a 64-wide default: exact. + ShaderEntry halves = entry("vs", false); + halves.wave32_halves = true; + CHECK(decide_subgroup_size(halves, caps).outcome == SubgroupOutcome::halves); + } + + // --- Smaller sizes than 32 (sizes 8..32, default 16): halves cannot help a wave cut below 32 lanes --------------- + { + SubgroupSizeCaps caps = amd(); + caps.min_size = 8; + caps.max_size = 32; + caps.default_size = 16; + caps.required_stages = VK_SHADER_STAGE_COMPUTE_BIT; + ShaderEntry halves = entry("vs", false); + halves.wave32_halves = true; + CHECK(decide_subgroup_size(halves, caps).outcome == SubgroupOutcome::unavailable); + // Default 32 there: works as it is, as for any wave32 shader. + caps.default_size = 32; + CHECK(decide_subgroup_size(halves, caps).outcome == SubgroupOutcome::device_default); + // A wave64 entry never takes the halves outcome, even if the field were set. + ShaderEntry w64 = entry("vs", true); + w64.wave32_halves = true; + CHECK(decide_subgroup_size(w64, amd()).outcome == SubgroupOutcome::device_default); } // --- Feature, limit and index edge cases ------------------------------------------------------------------------- diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index 94de20f26f..788dbfb028 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -46,6 +46,7 @@ from check import GET_LOD_TESTS, STORE_WORDS, get_lod_test, store_words_problem # TEST-184: image atomics and queries from check import wide_pixel_skip # ps_w64x_readlane: judged only where the fragment stage was required 64-wide from check import FMA_FUSED_ENV, judge_fma_fused # cs_fma_fused: strict under LEONIDA_FMA=khr, fused/split under glsl +import w32_vs_halves # noqa: E402 (vs_w32_*: wave32 invariants on wide vertex subgroups, as in check.py) def make_dxbc(chunks: list[tuple[bytes, bytes]]) -> bytes: @@ -581,7 +582,8 @@ def check_clip_half(raw_path: str, want_b: float, want_a: float) -> tuple[bool, "ps_interp_f16_high": "vs_f16_pack.asm", "ms_f16_pack": "ps_interp_f16_high.asm", "ps_interp_f32_mods": "vs_interp_consts.asm", "ps_interp_mov_mods": "vs_interp_consts.asm", SIGNED_MIP_TEST: "vs_ids.asm", - "vs_base_ids": "ps_flat.asm"} + "vs_base_ids": "ps_flat.asm", + **{name: "ps_clip_color.asm" for name in w32_vs_halves.FIXTURES}} DRAWN_WITH.update({name: "vs_ids.asm" for name in GET_LOD_TESTS}) @@ -1348,6 +1350,12 @@ def run_suite(a, work: str) -> int: else: ok, detail = check_clip_half(raw, 0.5, 1.0) results.append((name, ok, detail)) + elif name in w32_vs_halves.FIXTURES: + # Wave32 VS on wide vertex subgroups (runtime/test/shaders/w32_vs_halves.py): every wave32 invariant, + # whatever packing the driver chose, as check.py checks. + problem = w32_vs_halves.check(os.path.dirname(vk_harness), spirv_dir, name) + results.append((name, None if problem.startswith("SKIP") else not problem, + problem or "960 vertices: every wave32 invariant holds")) elif name == "vs_base_ids": # Zero-based v0 / v3 (the hardware's VS input VGPRs): drawn with firstVertex 16 and firstInstance 7, # ps_flat must still see vertex 0 of instance 0 (0x101), as check.py checks. diff --git a/tests/semantic/spirv_wave_interp.py b/tests/semantic/spirv_wave_interp.py index 70c8ee1537..af6af7740e 100644 --- a/tests/semantic/spirv_wave_interp.py +++ b/tests/semantic/spirv_wave_interp.py @@ -706,6 +706,15 @@ def eval(self, lane, res, op, a): for k in a[2:]: v = v[int(k)] return v + if op == "OpVectorExtractDynamic": + # SPIR-V 3.32.12: the component at Index; an Index outside the vector gives an undefined value. + v, i = self.val(lane, a[1]), self.int_of(lane, a[2]) + if not isinstance(v, tuple): + raise UnsupportedConstruct("OpVectorExtractDynamic of a non-vector") + if not 0 <= i < len(v): + raise UnsupportedConstruct(f"OpVectorExtractDynamic index {i} of a {len(v)}-component vector " + "(undefined)") + return v[i] if op == "OpCompositeInsert": v = list(self.val(lane, a[2])) if len(a) != 4: diff --git a/tests/semantic/test_vs_readfirstlane.py b/tests/semantic/test_vs_readfirstlane.py index c646e4f074..def7461c20 100644 --- a/tests/semantic/test_vs_readfirstlane.py +++ b/tests/semantic/test_vs_readfirstlane.py @@ -22,6 +22,7 @@ sys.path.insert(0, HERE) import support # noqa: E402,F401 (sets the tools path) from support import translate_listing # noqa: E402 +import rdna2spirv # noqa: E402 (support put tools/ on the path) import spirv_wave_interp as wi # noqa: E402 LITERAL_OPS = ("exp", "buffer_", "global_", "ds_", "image_") @@ -84,11 +85,26 @@ def test_first_lane_in_word_1_of_a_64_lane_subgroup(self): self.check(64, first) def test_all_four_ballot_words_are_read(self): - # Vulkan allows subgroups of up to 128 invocations (the interpreter runs 32 and 64), so all four words count. + # Vulkan allows subgroups of up to 128 invocations (the interpreter runs 32 and 64), so all four words count: + # a wave64 VS, and a wave32 VS translated as one wave per subgroup (--no-wave32-halves), read all four. + saved = rdna2spirv.WAVE32_HALVES + try: + rdna2spirv.WAVE32_HALVES = False + for asm in (self.check(64, 40), self.check(32, 6)): + bal = re.search(r"(%\w+) = OpGroupNonUniformBallot ", asm).group(1) + words = set(re.findall(rf"= OpCompositeExtract %uint {re.escape(bal)} (\d)\b", asm)) + self.assertEqual(words, {"0", "1", "2", "3"}) + finally: + rdna2spirv.WAVE32_HALVES = saved + + def test_a_wave32_vs_reads_its_own_waves_ballot_word(self): + # With halves (the default for wave32 VS, tests/semantic/test_wave32_vs_halves.py) the wave is 32 subgroup + # lanes: its word of the ballot is word SubgroupLocalInvocationId / 32, which reaches each of the four. asm = self.check(32, 6) bal = re.search(r"(%\w+) = OpGroupNonUniformBallot ", asm).group(1) - words = set(re.findall(rf"= OpCompositeExtract %uint {re.escape(bal)} (\d)\b", asm)) - self.assertEqual(words, {"0", "1", "2", "3"}) + m = re.search(rf"= OpVectorExtractDynamic %uint {re.escape(bal)} (%\w+)", asm) + self.assertIsNotNone(m) + self.assertRegex(asm, rf"{re.escape(m.group(1))} = OpShiftRightLogical %uint %\w+ %c5\b") def test_no_ballot_find_lsb_or_subgroup_size_in_a_vertex_shader(self): asm = self.check(32, 6) diff --git a/tests/semantic/test_wave32_vs_halves.py b/tests/semantic/test_wave32_vs_halves.py new file mode 100644 index 0000000000..f3ccf7d663 --- /dev/null +++ b/tests/semantic/test_wave32_vs_halves.py @@ -0,0 +1,185 @@ +"""Wave32 vertex shaders on vertex subgroups of 32 and 64 invocations (tools/rdna2spirv.py `Gen.halves`). + +The tested AMD Windows driver omits VERTEX from requiredSubgroupSizeStages and runs the vertex stage 64-wide (measured on an RX 7600, driver 26.11.2, by +runtime/test/shaders/w32_vs_halves.py). A wave32 VS then shares one subgroup with a second wave's worth of +vertices. With halves (the default), subgroup lanes 32k..32k+31 are one wave: the reference here is an independent +model of two wave32s of 32 lanes each, written from the RDNA2 ISA (v_mbcnt_lo, s_bcnt1, s_ff1, v_readfirstlane, +v_readlane, ds_bpermute, s_cbranch_vccz, writes to exec_lo), and the translated module runs through +spirv_wave_interp at 32 and 64 invocations. With --no-wave32-halves the 32-invocation run still matches and the +64-invocation run does not, which is the defect the default fixes. No GPU. +""" +import os +import re +import tempfile +import unittest +import warnings + +import support # noqa: F401 (puts tools/ on the path) +import rdna2spirv +from spirv_wave_interp import run_wave + +BASE = 1000 # vertex index of invocation 0 +VOTE_VERTEX = BASE + 37 # in the second wave of a 64-invocation subgroup + + +def sized(lines): + """Placeholder encodings of the right size, so branch offsets count dwords (as test_export_valid_mask).""" + out = [] + for line in lines: + op = line.split()[0] + vop3 = op.startswith(("v_mbcnt", "v_readlane", "v_cndmask_b32_e64")) or op.startswith("ds_") + literal = any(int(t, 16) > 64 for t in re.findall(r"0x([0-9a-f]+)", line)) + size = 8 if (op == "exp" or vop3 or literal) else 4 + out.append(f"{line} ; encoding: [" + ",".join(["0x00"] * size) + "]") + return out + + +PROLOGUE = ["v_mbcnt_lo_u32_b32 v6, -1, 0", "v_readfirstlane_b32 s20, v0", "v_mov_b32_e32 v9, s20"] +EPILOGUE = ["v_mov_b32_e32 v5, 0", "exp pos0 v5, v5, v5, v5 done", "exp param0 v6, v7, v8, v9", + "exp param1 v10, v11, v12, v13", "s_endpgm"] + +PROGRAMS = { + # param0 = (lane, s_bcnt1 exec_lo, 0, key); param1 = 0 + "lane": ["s_bcnt1_i32_b32 s4, exec_lo", "v_mov_b32_e32 v7, s4", "v_mov_b32_e32 v8, 0", + "v_mov_b32_e32 v10, 0", "v_mov_b32_e32 v11, 0", "v_mov_b32_e32 v12, 0", "v_mov_b32_e32 v13, 0"], + # VCC = v % 4 == 1. param0 = (lane, rank, count, key); param1 = (first, sel, 0, 0) + "ballot": ["v_and_b32_e32 v4, 3, v0", "v_cmp_eq_u32_e32 vcc_lo, 1, v4", "v_mbcnt_lo_u32_b32 v7, vcc_lo, 0", + "s_bcnt1_i32_b32 s6, vcc_lo", "v_mov_b32_e32 v8, s6", "s_ff1_i32_b32 s7, vcc_lo", + "v_mov_b32_e32 v10, s7", "v_cndmask_b32_e64 v11, 0, 1, vcc_lo", "v_mov_b32_e32 v12, 0", + "v_mov_b32_e32 v13, 0"], + # param0 = (lane, readlane 5, readlane 31, key); param1 = (bpermute lane ^ 1, bpermute (lane + 1) & 31, 0, 0) + "shuffle": ["v_readlane_b32 s6, v0, 5", "v_mov_b32_e32 v7, s6", "v_readlane_b32 s7, v0, 31", + "v_mov_b32_e32 v8, s7", "v_xor_b32_e32 v14, 1, v6", "v_lshlrev_b32_e32 v14, 2, v14", + "v_add_nc_u32_e32 v15, 1, v6", "v_and_b32_e32 v15, 31, v15", "v_lshlrev_b32_e32 v15, 2, v15", + "ds_bpermute_b32 v10, v14, v0", "ds_bpermute_b32 v11, v15, v0", "s_waitcnt lgkmcnt(0)", + "v_mov_b32_e32 v12, 0", "v_mov_b32_e32 v13, 0"], + # param0 = (lane, s5 after s_cbranch_vccz on v == VOTE_VERTEX, low16 under exec_lo = 0xffff, key); param1 = 0 + "vote": ["s_mov_b32 s5, 0", f"v_mov_b32_e32 v4, 0x{VOTE_VERTEX:x}", "v_cmp_eq_u32_e32 vcc_lo, v4, v0", + "s_cbranch_vccz 1", "s_mov_b32 s5, 7", "v_mov_b32_e32 v7, s5", "s_mov_b32 s10, exec_lo", + "v_mov_b32_e32 v8, 0", "s_mov_b32 exec_lo, 0xffff", "v_mov_b32_e32 v8, 1", "s_mov_b32 exec_lo, s10", + "v_mov_b32_e32 v10, 0", "v_mov_b32_e32 v11, 0", "v_mov_b32_e32 v12, 0", "v_mov_b32_e32 v13, 0"], +} + + +def model(name, invocations): + """(param0, param1) per invocation for two (or one) independent wave32s of 32 lanes each.""" + rows = [] + for inv in range(invocations): + wave, lane = divmod(inv, 32) + vs = [BASE + 32 * wave + l for l in range(32)] # the wave's vertices, by lane + v, key = vs[lane], vs[0] + if name == "lane": + rows.append(((lane, 32, 0, key), (0, 0, 0, 0))) + elif name == "ballot": + sel = [l for l in range(32) if vs[l] % 4 == 1] + rank = sum(1 for l in sel if l < lane) + first = sel[0] if sel else 0xFFFFFFFF + rows.append(((lane, rank, len(sel), key), (first, int(v % 4 == 1), 0, 0))) + elif name == "shuffle": + rows.append(((lane, vs[5], vs[31], key), (vs[lane ^ 1], vs[(lane + 1) & 31], 0, 0))) + elif name == "vote": + rows.append(((lane, 7 if VOTE_VERTEX in vs else 0, int(lane < 16), key), (0, 0, 0, 0))) + return rows + + +def translate(name, halves): + return translate_program(name, PROLOGUE + PROGRAMS[name] + EPILOGUE, halves) + + +def translate_program(name, program, halves): + body = sized(program) + asm = f"; vs_w32_{name}\n" + "".join(f"\t{ln}\n" for ln in body) + saved = rdna2spirv.WAVE32_HALVES + rdna2spirv.WAVE32_HALVES = halves + try: + with tempfile.TemporaryDirectory() as tmp: + os.mkdir(os.path.join(tmp, "disasm")) + src = os.path.join(tmp, "disasm", f"vs_w32_{name}.s") + with open(src, "w", encoding="utf-8", newline="\n") as f: + f.write(asm) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ResourceWarning) + return rdna2spirv.translate(src) + finally: + rdna2spirv.WAVE32_HALVES = saved + + +def run(spv, invocations): + res = run_wave(spv, wave=invocations, builtins={"VertexIndex": lambda lane: BASE + lane, + "InstanceIndex": lambda lane: 0}) + return [(o["%out_param0"], o["%out_param1"]) for o in res["outputs"]] + + +class Wave32VertexHalves(unittest.TestCase): + def check(self, name): + spv = translate(name, halves=True) + for n in (32, 64): + with self.subTest(program=name, invocations=n): + self.assertEqual(run(spv, n), model(name, n)) + + def test_lane_count_and_first_lane(self): + self.check("lane") + + def test_ballot_rank_count_first(self): + self.check("ballot") + + def test_readlane_and_bpermute_stay_in_the_wave(self): + self.check("shuffle") + + def test_vccz_vote_and_exec_lo_write(self): + self.check("vote") + + def test_bpermute_masks_the_source_and_preserves_inactive_destinations(self): + program = ["v_mbcnt_lo_u32_b32 v6, -1, 0", "v_mov_b32_e32 v7, 42", + "v_and_b32_e32 v4, 2, v6", "v_add_nc_u32_e32 v4, 1, v4", + "v_lshlrev_b32_e32 v4, 2, v4", "s_mov_b32 exec_lo, 0xfffffffd", + "ds_bpermute_b32 v7, v4, v0", "s_waitcnt lgkmcnt(0)", "s_mov_b32 exec_lo, -1"] + spv = translate_program("inactive_gather", program + EPILOGUE, True) + for size in (32, 64): + rows = run(spv, size) + for i, (param0, _) in enumerate(rows): + lane = i % 32 + # Source lane 1 is disabled. Source lane 3 holds a different vertex in each wave. + want = BASE + i - lane + 3 if lane & 2 else 0 + if lane == 1: + want = 42 + self.assertEqual(param0[1], want, (size, i)) + + def test_partitioned_capabilities_follow_the_operations(self): + exports = ["exp pos0 v0, v0, v0, v0 done", "exp param0 v6, v6, v6, v6", "s_endpgm"] + cases = [ + ("plain", ["v_mov_b32_e32 v6, v0"], set()), + ("lane_only", ["v_mbcnt_lo_u32_b32 v6, -1, 0"], {""}), + ("vote_only", ["v_cmp_eq_u32_e32 vcc_lo, 37, v0", "s_cbranch_vccz 1", + "s_mov_b32 s5, 7", "v_mov_b32_e32 v6, s5"], {"", "Ballot"}), + ("mask_only", ["s_bcnt1_i32_b32 s5, exec_lo", "v_mov_b32_e32 v6, s5"], {"", "Ballot"}), + ("first", ["v_readfirstlane_b32 s5, v0", "v_mov_b32_e32 v6, s5"], {"", "Ballot", "Shuffle"}), + ("read", ["v_readlane_b32 s5, v0, 5", "v_mov_b32_e32 v6, s5"], {"", "Shuffle"}), + ] + for name, program, capabilities in cases: + with self.subTest(name=name): + spv = translate_program(name, program + exports, True) + self.assertEqual(set(re.findall(r"OpCapability GroupNonUniform(\w*)", spv)), capabilities) + + def test_reads_this_waves_ballot_word(self): + spv = translate("lane", halves=True) + self.assertIn("OpVectorExtractDynamic", spv) + + +class WithoutHalves(unittest.TestCase): + """--no-wave32-halves: what main did. Exact on 32 invocations, wrong on 64 (each program).""" + + def test_exact_on_32_wrong_on_64(self): + for name in PROGRAMS: + spv = translate(name, halves=False) + with self.subTest(program=name, invocations=32): + self.assertEqual(run(spv, 32), model(name, 32)) + with self.subTest(program=name, invocations=64): + got, want = run(spv, 64), model(name, 64) + self.assertNotEqual(got, want) + wrong = sum(1 for g, w in zip(got, want) if g != w) + self.assertGreaterEqual(wrong, 32, f"{name}: {wrong} of 64 invocations differ") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_make_game_translator_flags.py b/tests/test_make_game_translator_flags.py index 13322b89fe..0e6a3d4410 100644 --- a/tests/test_make_game_translator_flags.py +++ b/tests/test_make_game_translator_flags.py @@ -38,6 +38,23 @@ def test_all_flags_in_record_order(self): self.assertEqual(make_game.fallback_flags(self.args_with(*reversed(ALL_FLAGS))), ALL_FLAGS) +class Wave32HalvesFallbackTest(unittest.TestCase): + """--no-wave32-halves is a forwarded fallback flag, chosen by itself on MoltenVK (no vertex subgroup lane).""" + + def test_is_a_fallback_flag(self): + self.assertIn(("--no-wave32-halves", "no_wave32_halves"), make_game.FALLBACK_FLAGS) + + def test_moltenvk_has_no_vertex_lane(self): + self.assertTrue(make_game.wave32_halves_fallback({"driver_id": 14, "vertex_ballot": True})) + + def test_missing_vertex_ballot_uses_fallback(self): + self.assertTrue(make_game.wave32_halves_fallback({"driver_id": 1, "vertex_ballot": False})) + + def test_other_drivers_and_unknown_keep_halves(self): + for info in ({"driver_id": 1}, {"driver_id": 3}, {"driver_id": None}, {}): + self.assertFalse(make_game.wave32_halves_fallback(info), info) + + class TranslateFallbacksTest(unittest.TestCase): """translate() passes the fallback flags to every shard, and re-plans when they change.""" diff --git a/tests/test_shader_checks.py b/tests/test_shader_checks.py index dbb426249c..18d77de01e 100644 --- a/tests/test_shader_checks.py +++ b/tests/test_shader_checks.py @@ -35,7 +35,7 @@ + len(check.PIXEL_TESTS) + len(check.CLIP_TESTS) + len(check.BOUNDS) + len(check.GLOBAL_OFFSET) + len(check.MIP_TEST_PASSES) + len(check.GRADIENT_TESTS) + len(check.STORE_WORDS) + len(check.GET_LOD_TESTS) - + len(check.TEXTURE_CONSTANTS) + 13) # three mesh fixtures, ps_tex, ps_imgatomic, five compute fixtures, + + len(check.TEXTURE_CONSTANTS) + len(check.W32_VS_FIXTURES) + 13) # three mesh fixtures, ps_tex, ps_imgatomic, five compute fixtures, # ps_ssharp, vs_base_ids and the standalone cs_fmt_d16_xyz / cs_heap_init dumps (net one more case) CVT = {bits: [u, s] for bits, u, s in check.CVT_F32_SAT_CASES} @@ -174,6 +174,7 @@ def harness(_tool, shader, *args, env=None): patch.object(check, "texture_gradient_a16_test", return_value=""), patch.object(check, "texture_constant_test", return_value=""), patch.object(check, "base_ids_test", return_value=""), + patch.object(check, "w32_vs_halves_test", return_value=""), patch.object(check, "get_lod_test", return_value=""), patch.object(check, "sampler_test", return_value=""), contextlib.redirect_stdout(output)): diff --git a/tests/test_vk_subgroup_info.py b/tests/test_vk_subgroup_info.py index 8de7264f26..d71fa0bc93 100644 --- a/tests/test_vk_subgroup_info.py +++ b/tests/test_vk_subgroup_info.py @@ -58,6 +58,7 @@ class FakeDevice: buffer_device_address: bool = True subgroup_size_control: bool = True queue_flags: tuple[int, ...] = (vk_info.VK_QUEUE_GRAPHICS_BIT,) + subgroup_operations: int = 0 subgroup_size: int = 32 subgroup_supported_stages: int = ( vk_info.VK_SHADER_STAGE_COMPUTE_BIT | vk_info.VK_SHADER_STAGE_MESH_BIT_EXT @@ -199,6 +200,7 @@ def _get_physical_device_properties2(self, phys_dev, p_props): subgroup = vk_info.SubgroupProperties.from_address(node_addr) subgroup.subgroupSize = dev.subgroup_size subgroup.supportedStages = dev.subgroup_supported_stages + subgroup.supportedOperations = dev.subgroup_operations elif stype == vk_info.VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_PROPERTIES: found_sg = True sg = vk_info.SubgroupSizeControl.from_address(node_addr) @@ -794,6 +796,7 @@ def test_native64_conditions_and_boundaries(self): "mesh_in_required_stages": want_mesh, "compute_in_supported_stages": True, "mesh_in_supported_stages": True, + "vertex_ballot": False, "native64_compute": want_native64 or label == "missing_mesh_stage_bit", "native64": want_native64, "per_vertex_inputs": True, @@ -805,6 +808,13 @@ def test_native64_conditions_and_boundaries(self): "rdna2_amd_windows": False, }) + def test_vertex_ballot_requires_both_stage_and_operation(self): + for stage in (0, vk_info.VK_SHADER_STAGE_VERTEX_BIT): + for ops in (2, 2 | vk_info.VK_SUBGROUP_FEATURE_BALLOT_BIT): + with self.subTest(stage=stage, operations=ops): + result, _ = self._run_query(FakeDevice(subgroup_supported_stages=stage, subgroup_operations=ops)) + self.assertEqual(result["vertex_ballot"], bool(stage and ops & 8)) + def test_max_push_constants_size(self): """limits.maxPushConstantsSize is read from VkPhysicalDeviceProperties (offset 328 on 64-bit).""" for limit in (128, 256, 4096): diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 809fc1b4b0..368b27f39b 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -46,6 +46,9 @@ # (SHADER-299, docs/design.md "Control flow"). Both forms are equivalent; only the routing differs. MAX_STRUCTURED_DEPTH = 16 WAVE64_EMULATE = False # --wave64-emulate: wave64 compute/mesh shaders exact on any subgroup size (Gen.x_round) +# Wave32 vertex shaders keep each wave in its own 32-lane part of the subgroup (Gen.halves; --no-wave32-halves turns +# it off). The tested RX 7600 driver runs the vertex stage 64-wide. +WAVE32_HALVES = True # --max-shared-memory: a cap on a compute shader's Workgroup variables, LDS plus %x_buf (SHADER-309, #1721). The # default is the hard cap: 64 KiB, RDNA2's LDS per workgroup and the largest maxComputeSharedMemorySize drivers # report (RADV, NVIDIA). It is not the device limit: the AMD Windows (RDNA4) and Intel drivers report 32768, the @@ -234,6 +237,7 @@ def __init__(self, stage): self.uses_perm = False # emulate: ds_permute_b32 parks its winning source lane in %x_perm self.uses_tex = False self.uses_subgroup = False + self.uses_shuffle = False self.uses_tex_array = False self.uses_storage = False self.uses_query = False @@ -297,6 +301,7 @@ def __init__(self, stage): self.emulate_plan = None # emulate: structured plan from wave64_emulate_opt.plan_structured_emulation self.mini_segs = defaultdict(list) # emulate_plan: mini_idx -> continuation segment ids self.tail_segs = [] # emulate_plan: continuation segment ids belonging to tail_scheduler + self.halves = False # wave32 VS: every 32 subgroup lanes are one wave (see wave_lane, half_base) self.x_seg = 0 # emulate: number of the next continuation segment (past the block numbers) self.x_marks = [] # emulate: (index into body, segment) where a segment of the current block ends self.x_segs = {} # emulate: continuation segment -> its SPIR-V lines @@ -3910,6 +3915,9 @@ def wave_lane(self): lane = self.tmp() if self.stage in ("cs", "ms"): self.emit(f"{lane} = OpBitwiseAnd %uint {self.local_index()} {self.cu(63 if self.wave64 else 31)}") + elif self.halves: + sg = self.subgroup_lane() + self.emit(f"{lane} = OpBitwiseAnd %uint {sg} {self.cu(31)}") else: self.uses_subgroup = True self.emit(f"{lane} = OpLoad %uint %sg_lane") @@ -3939,6 +3947,32 @@ def ballot_lsb_by_words(self, bal): r = pick return r + # ---- wave32 halves (Gen.halves, wave32 vertex shaders) ---- + # The tested RX 7600 driver runs vertex shaders 64-wide and omits VERTEX from requiredSubgroupSizeStages. + # Each group of 32 physical lanes is one guest wave. Votes use the corresponding word of a ballot, + # and reads of a logical lane add the physical base of the caller's wave. + def half_base(self): + """halves: the subgroup lane of this wave's lane 0 (the subgroup lane with its low 5 bits cleared).""" + sg, r = self.subgroup_lane(), self.tmp() + self.emit(f"{r} = OpBitwiseAnd %uint {sg} {self.cu(0xFFFFFFE0)}") + return r + + def half_ballot(self, b): + """halves: the 32 bits of a ballot of bool `b` that are this wave's lanes (ballot word subgroup lane / 32).""" + self.uses_subgroup = self.uses_ballot = True + bal, sg, i, r = self.tmp(), self.subgroup_lane(), self.tmp(), self.tmp() + self.emit(f"{bal} = OpGroupNonUniformBallot %v4uint_bal {self.cu(3)} {b}") + self.emit(f"{i} = OpShiftRightLogical %uint {sg} {self.cu(5)}") + self.emit(f"{r} = OpVectorExtractDynamic %uint {bal} {i}") + return r + + def half_lane(self, src): + """halves: subgroup lane of lane `src` (0..31, or a subgroup lane) of this invocation's wave.""" + low, r = self.tmp(), self.tmp() + self.emit(f"{low} = OpBitwiseAnd %uint {src} {self.cu(31)}") + self.emit(f"{r} = OpBitwiseOr %uint {low} {self.half_base()}") + return r + # ---- wave64 emulation (--wave64-emulate) ---- # A wave64 compute or mesh shader runs exact on any subgroup size. Each lane is one invocation as usual, but no # subgroup operation is used: everything a lane needs from the rest of its wave goes through a Workgroup buffer @@ -4260,6 +4294,14 @@ def x_memory_order(self, op): def g_vote(self, r, kind, b): """r = OpGroupNonUniform{Any,All} of bool b over the wave.""" + if self.halves: + # This wave's word of the ballot: Any = some bit, All = every running invocation of the wave voted yes. + w = self.half_ballot(b) + if kind == "Any": + self.emit(f"{r} = OpINotEqual %bool {w} {self.cu(0)}") + else: + self.emit(f"{r} = OpIEqual %bool {w} {self.half_ballot('%true')}") + return if not self.emulate: self.emit(f"{r} = OpGroupNonUniform{kind} %bool {self.cu(3)} {b}") return @@ -4272,10 +4314,16 @@ def g_vote(self, r, kind, b): lo = self.x_round(bits=(bit, None))[1][0] self.emit(f"{r} = {'OpIEqual' if kind == 'All' else 'OpINotEqual'} %bool {lo} {self.cu(0)}") + def subgroup_shuffle(self, result, value, physical_lane): + self.uses_shuffle = True + self.emit(f"{result} = OpGroupNonUniformShuffle %uint {self.cu(3)} {value} {physical_lane}") + def g_shuffle(self, r, v, src): """r = v of lane src of this wave (OpGroupNonUniformShuffle, or any emulated lane 0-63).""" + if self.halves: + src = self.half_lane(src) if not self.emulate: - self.emit(f"{r} = OpGroupNonUniformShuffle %uint %c3 {v} {src}") + self.subgroup_shuffle(r, v, src) return read = self.x_round(data=v)[0] self.emit(f"{r} = OpCopyObject %uint {read(src)}") @@ -4292,7 +4340,7 @@ def ds_lane_read(self, dst: dict, data: str, src: str, lane: str) -> None: self.emit(f"{ballot} = OpGroupNonUniformBallot %v4uint_bal %c3 %true") self.emit(f"{present} = OpGroupNonUniformBallotBitExtract %bool %c3 {ballot} {src}") self.emit(f"{safe_src} = OpSelect %uint {present} {src} {lane}") - self.emit(f"{shuffled} = OpGroupNonUniformShuffle %uint %c3 {value} {safe_src}") + self.subgroup_shuffle(shuffled, value, safe_src) self.emit(f"{mask} = OpSelect %uint {present} {self.cu(0xFFFFFFFF)} {self.cu(0)}") self.emit(f"{result} = OpBitwiseAnd %uint {shuffled} {mask}") self.uses_subgroup = self.uses_ballot = True @@ -4358,20 +4406,22 @@ def ds_permute(self, a, mods): sgl = self.tmp() self.emit(f"{sgl} = OpLoad %uint %sg_lane") self.emit(f"{half} = OpBitwiseAnd %uint {sgl} {self.cu(32)}") + elif self.halves: + self.emit(f"{half} = OpCopyObject %uint {self.half_base()}") bal = self.tmp() self.emit(f"{bal} = OpGroupNonUniformBallot %v4uint_bal %c3 %true") acc = self.cu(0) for j in range(32): src = self.cu(j) - if self.wave64: + if self.wave64 or self.halves: src = self.tmp() self.emit(f"{src} = OpBitwiseOr %uint {half} {self.cu(j)}") ex, shv, v, shd, hit, nxt = (self.tmp() for _ in range(6)) # a shuffle from a lane that isn't running (the missing lanes of a partial wave) is undefined self.emit(f"{ex} = OpGroupNonUniformBallotBitExtract %bool %c3 {bal} {src}") - self.emit(f"{shv} = OpGroupNonUniformShuffle %uint %c3 {tp} {src}") + self.subgroup_shuffle(shv, tp, src) self.emit(f"{v} = OpSelect %uint {ex} {shv} {self.cu(0)}") - self.emit(f"{shd} = OpGroupNonUniformShuffle %uint %c3 {dat} {src}") + self.subgroup_shuffle(shd, dat, src) self.emit(f"{hit} = OpIEqual %bool {v} {mine}") self.emit(f"{nxt} = OpSelect %uint {hit} {shd} {acc}") acc = nxt @@ -4616,6 +4666,9 @@ def wave_mask(self, a): if key is not None: self.x_mcache[key] = res return res + if self.halves: + # This wave's 32 bits; a wave32 mask has no high word (lanes 32..63 of the subgroup are another wave). + return self.half_ballot(mine), self.cu(0) lane = self.wave_lane() low, sh, bit, b, lo_in, hi_in, lo, hi = (self.tmp() for _ in range(8)) self.emit(f"{low} = OpULessThan %bool {lane} {self.cu(32)}") @@ -5357,7 +5410,7 @@ def selectors(key, count, limit): if src.get("k") == "vgpr": self.uses_subgroup = True shuffled = self.tmp() - self.emit(f"{shuffled} = OpGroupNonUniformShuffle %uint {self.cu(3)} {src_val} {safe_sg}") + self.subgroup_shuffle(shuffled, src_val, safe_sg) else: shuffled = src_val @@ -5626,6 +5679,17 @@ def _insn(self, ins): self.emit(f"{first} = OpSelect %uint {lz} {l} {fh}") self.dst(a[0], read(first)) return + if self.halves: + # The lowest set bit of this wave's ballot word, as a subgroup lane; lane 0 of the wave if none. + v, w = self.src_u(a[1]), self.half_ballot(self.active_b()) + lsb, any_, rel, first, r = (self.tmp() for _ in range(5)) + self.emit(f"{lsb} = OpExtInst %uint %glsl FindILsb {w}") + self.emit(f"{any_} = OpINotEqual %bool {w} {self.cu(0)}") + self.emit(f"{rel} = OpSelect %uint {any_} {lsb} {self.cu(0)}") + self.emit(f"{first} = OpBitwiseOr %uint {rel} {self.half_base()}") + self.subgroup_shuffle(r, v, first) + self.dst(a[0], r) + return self.uses_subgroup = self.uses_ballot = self.uses_vote = True v, act = self.src_u(a[1]), self.active_b() bal, lsb, any_, first, r = (self.tmp() for _ in range(5)) @@ -5636,7 +5700,7 @@ def _insn(self, ins): self.emit(f"{lsb} = OpGroupNonUniformBallotFindLSB %uint {self.cu(3)} {bal}") self.emit(f"{any_} = OpGroupNonUniformAny %bool {self.cu(3)} {act}") self.emit(f"{first} = OpSelect %uint {any_} {lsb} {self.cu(0)}") - self.emit(f"{r} = OpGroupNonUniformShuffle %uint {self.cu(3)} {v} {first}") + self.subgroup_shuffle(r, v, first) self.dst(a[0], r) elif op in ("image_sample_o", "image_sample_lz_o", "image_sample_l_o", "image_sample_b_o", "image_sample_c_lz_o") or op in ("image_sample", "image_sample_lz", "image_sample_l", "image_sample_b", "image_sample_c_lz", @@ -6043,6 +6107,7 @@ def sel(c, t, f): if op.endswith("b64") or "bcnt1" in op: # s_bcnt1_i32_b32 counts the high word too: for a lane mask of a wave32 shader running in a 64-lane # subgroup (graphics stages can't request 32) the other lanes' bits are there; otherwise hi is 0. + # A wave32 VS with `halves` has hi = 0 (wave_mask gives its own wave's word), so it counts its wave. # s_bcnt0_i32_b32 counts zeros of the low word only (~0 in the high word would add 32). self.emit(f"{c2} = OpBitCount %uint {hi}") self.emit(f"{r} = OpIAdd %uint {c1} {c2}") @@ -6355,10 +6420,11 @@ def f64(sv): self.emit(f"{ln} = OpShiftRightLogical %uint {s1} {self.cu(2)}") self.emit(f"{src} = OpBitwiseAnd %uint {ln} {self.cu(31)}") self.sub_lane(lane) - if self.wave64: - # RDNA2 ISA 10.4.4: each half-wave permutes independently. + if self.wave64 or self.halves: + # Wave64 permutes each half independently (ISA 10.4.4). Partitioned VSs use the full + # physical base so the third and fourth waves of a 128-wide subgroup also stay local. half, full_src = self.tmp(), self.tmp() - self.emit(f"{half} = OpBitwiseAnd %uint {lane} {self.cu(32)}") + self.emit(f"{half} = OpBitwiseAnd %uint {lane} {self.cu(0xFFFFFFE0 if self.halves else 32)}") self.emit(f"{full_src} = OpBitwiseOr %uint {half} {src}") src = full_src self.ds_lane_read(d, dat, src, lane) @@ -6413,8 +6479,9 @@ def f64(sv): if slot and slot[1:] in self.parked: # somewhere a mask is fetched back from this lane: keep ours self.store_reg("sgpr", self.parked[slot[1:]], val) me, m, eq, old, r = (self.tmp() for _ in range(5)) - if self.stage in ("cs", "ms"): - # The hardware lane: lanes 32-63 of a wave64 are lanes 0-31 of a second 32-wide subgroup. + if self.stage in ("cs", "ms") or self.halves: + # The hardware lane: lanes 32-63 of a wave64 are lanes 0-31 of a second 32-wide subgroup (halves: of + # a 64-wide subgroup, a second wave32). self.emit(f"{me} = OpCopyObject %uint {self.wave_lane()}") else: self.emit(f"{me} = OpLoad %uint %sg_lane") @@ -11949,16 +12016,19 @@ def assemble(gen): for i in range(USER_SGPRS): # index constants for the user-data copy at entry gen.cu(i) # SPIR-V module layout: every OpCapability, then every OpExtension, then imports. + # In a partitioned VS the lane input requires Basic. Only an actual shuffle needs Shuffle; + # votes and mask reductions use a ballot word. Keep fallback modules byte-compatible. + shuffle = sg and (gen.uses_shuffle or not gen.halves) caps = ["Shader"] + (["Int64", "PhysicalStorageBufferAddresses"] if psb else []) + \ - (["RuntimeDescriptorArray"] if tex else []) + (["GroupNonUniform", "GroupNonUniformShuffle"] if sg else []) + \ - (["ImageQuery"] if gen.uses_query else []) + (["Sampled1D"] if gen.uses_tex_1d else []) + \ + (["RuntimeDescriptorArray"] if tex else []) + (["GroupNonUniform"] if sg else []) + \ + (["GroupNonUniformShuffle"] if shuffle else []) + (["ImageQuery"] if gen.uses_query else []) + (["Sampled1D"] if gen.uses_tex_1d else []) + \ (["MinLod"] if gen.uses_minlod else []) + (["ImageGatherExtended"] if gen.uses_img_offset else []) + \ (["FragmentBarycentricKHR"] if bary_builtin else []) - if gen.uses_vote: + if gen.uses_vote and not gen.halves: caps += [c for c in ("GroupNonUniform", "GroupNonUniformVote") if c not in caps] if gen.uses_ballot or gen.uses_bcast_first: caps += [c for c in ("GroupNonUniform", "GroupNonUniformBallot") if c not in caps] - if gen.uses_wave_bits: + if gen.uses_wave_bits and not gen.halves: caps += [c for c in ("GroupNonUniform", "GroupNonUniformArithmetic") if c not in caps] if gen.uses_quad: caps += [c for c in ("GroupNonUniform", "GroupNonUniformQuad") if c not in caps] @@ -13815,6 +13885,8 @@ def translate(path): insns = [i for i in insns if base_op(i["op"]) != "s_swappc_b64"] user_limit = g.cs["user"] if g.cs else USER_SGPRS sys_sgprs = (3,) if stage in ("ms", "gs") else () + if WAVE32_HALVES and not g.wave64 and stage == "vs": + g.halves = True if WAVE64_EMULATE and g.wave64 and stage in ("cs", "ms"): g.emulate = True size = (g.cs or g.ms)["size"] @@ -14621,6 +14693,9 @@ def shader_meta(g, asm, src_path=None, fssm_path=None): m["wave64_graphics_reasons"] = g.w64g["reasons"] if g.w64g["idioms"]: m["wave64_graphics_idioms"] = g.w64g["idioms"] + if g.halves: + # The runtime can accept wide vertex subgroups for these partitioned lane operations. + m["wave32_halves"] = True if g.emulate: # Exact on any subgroup size: no subgroup operation, cross-lane data in %x_buf (workgroup memory). m["wave64_exchange"] = "workgroup" @@ -14925,6 +15000,8 @@ def main(): ap.add_argument("--wave64-emulate", action="store_true", help="wave64 compute and mesh shaders exact on any subgroup size (32-wide NVIDIA, Intel): " "cross-lane operations go through workgroup memory instead of subgroup operations") + ap.add_argument("--no-wave32-halves", action="store_true", + help="translate wave32 vertex shaders as one wave per subgroup instead of one wave per 32 subgroup lanes") ap.add_argument("--wave64-graphics", choices=("warn", "error", "off"), default="warn", help="wave64 vertex, pixel and geometry shaders that are not exact on 32-wide subgroups (tier C of " "tools/wave64_halves.py): warn = count them in the summary and mark them in the index, " @@ -14975,7 +15052,7 @@ def main(): if ancestor and not os.path.isdir(ancestor): ap.error(f"cannot create {a.out}: {ancestor} is a file, not a folder") MAX_SHARED_BYTES = a.max_shared_memory - global STRUCTURED, WAVE64_EMULATE, WAVE64_GRAPHICS, BARY_FALLBACK, TEXEL_OFFSET_FALLBACK, MESH_COMPUTE, FMA_KHR, F16_HALVES + global STRUCTURED, WAVE64_EMULATE, WAVE32_HALVES, WAVE64_GRAPHICS, BARY_FALLBACK, TEXEL_OFFSET_FALLBACK, MESH_COMPUTE, FMA_KHR, F16_HALVES global PC_TAIL_UBO PC_TAIL_UBO = a.pc_tail_ubo FMA_KHR = a.fma == "khr" @@ -14983,6 +15060,7 @@ def main(): global FLOAT_CONTROLS FLOAT_CONTROLS = not a.no_float_controls WAVE64_EMULATE = a.wave64_emulate + WAVE32_HALVES = not a.no_wave32_halves WAVE64_GRAPHICS = a.wave64_graphics BARY_FALLBACK = a.bary_fallback TEXEL_OFFSET_FALLBACK = a.texel_offset_fallback diff --git a/tools/vk_subgroup_info.py b/tools/vk_subgroup_info.py index f7e3e0223e..e27d9de51e 100644 --- a/tools/vk_subgroup_info.py +++ b/tools/vk_subgroup_info.py @@ -44,6 +44,8 @@ VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO = 1 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2 = 1000059000 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2 = 1000059001 +VK_SHADER_STAGE_VERTEX_BIT = 0x1 +VK_SUBGROUP_FEATURE_BALLOT_BIT = 0x8 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES = 1000094000 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES = 51 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES = 53 @@ -285,7 +287,8 @@ def query() -> dict: if rank > chosen_rank: chosen_rank = rank chosen = (dev_name, - subgroup.subgroupSize, subgroup.supportedStages, sg.minSubgroupSize, sg.maxSubgroupSize, + subgroup.subgroupSize, subgroup.supportedStages, subgroup.supportedOperations, + sg.minSubgroupSize, sg.maxSubgroupSize, sg.requiredSubgroupSizeStages, bool(u32(f13, F13_SUBGROUP_SIZE_CONTROL)), bool(u32(bary, 16)) and u32(drv, 16) != VK_DRIVER_ID_MOLTENVK, int.from_bytes(raw[PROPS_MAX_PUSH_CONSTANTS_SIZE:PROPS_MAX_PUSH_CONSTANTS_SIZE + 4], "little"), @@ -298,7 +301,7 @@ def query() -> dict: "the runtime needs matches" ) raise RuntimeError("no Vulkan 1.3 GPU with the features and graphics queue the runtime needs") - (name, subgroup_size, supported_stages, lo, hi, required_stages, sgc, per_vertex, + (name, subgroup_size, supported_stages, operations, lo, hi, required_stages, sgc, per_vertex, max_push_constants_size, vendor, device, driver) = chosen compute_required = bool(required_stages & VK_SHADER_STAGE_COMPUTE_BIT) mesh_required = bool(required_stages & VK_SHADER_STAGE_MESH_BIT_EXT) @@ -318,6 +321,7 @@ def query() -> dict: "mesh_in_required_stages": mesh_required, "compute_in_supported_stages": compute_supported, "mesh_in_supported_stages": mesh_supported, + "vertex_ballot": bool(supported_stages & VK_SHADER_STAGE_VERTEX_BIT and operations & VK_SUBGROUP_FEATURE_BALLOT_BIT), "native64_compute": compute64, "native64": compute64 and mesh64, "per_vertex_inputs": per_vertex,