From df294dd8a1470b22a8300c951276f2f39b3abfe0 Mon Sep 17 00:00:00 2001 From: andretuta Date: Thu, 26 Nov 2026 22:11:21 -0300 Subject: [PATCH] rdna2spirv: preserve f16 denormals, NaN payloads, and bit-exact clamp in conversions (SHADER-CVT-F16-DENORM-AND-MODS) Route v_cvt_f32_f16 through f16_in_bits so SDWA/DPP half selection, subnormals, neg/abs, and IEEE=0 NaN sign/payload bits are preserved without raw UnpackHalf2x16 flush risk, and clamp v_cvt_f16_f32 and v_div_fixup_f16 directly on rounded f16 bits via shared clamp_f16_bits. Verified on RTX 3060 (driver 617.14, native + --wave64-emulate: fixed first word 0x7FFFFFFF -> 0xFFC4A000 on cs_w32_cvt_f16_mods), 13/13 new semantic tests, 501-module semantic suite (6,385 passed, 0 failed), and 100/100 real corpus shaders passing spirv-val. AI-assisted: Codex gpt-6.2-sol + Antigravity gemini-4-neon. --- docs/design.md | 2 +- runtime/test/shaders/check.py | 4 + runtime/test/shaders/cs_w32_cvt_f16_mods.asm | 44 +++++ scripts/run_gpu_tests.py | 9 +- tests/semantic/test_cvt_f16_denorm_mods.py | 183 +++++++++++++++++++ tools/rdna2spirv.py | 80 ++++---- 6 files changed, 278 insertions(+), 44 deletions(-) create mode 100644 runtime/test/shaders/cs_w32_cvt_f16_mods.asm create mode 100644 tests/semantic/test_cvt_f16_denorm_mods.py diff --git a/docs/design.md b/docs/design.md index 7bff52e7f9..ebbe429e77 100644 --- a/docs/design.md +++ b/docs/design.md @@ -523,7 +523,7 @@ How the generated SPIR-V expects the runtime to work: | 16-bit interpolation without `PerVertexKHR` (`--f16-interp-fallback`) | MoltenVK reports `fragmentShaderBarycentric` but can't create a pipeline with the row above's inputs: its SPIR-V to MSL conversion stops with "PerVertexKHR decoration is not supported in MSL" (MoltenVK 1.4.2 on an Apple A18 Pro and, reported by @DomasUrbonas in #166, an M4 Pro), so `ps_interp_f16_high` failed on every Mac. With the flag no `PerVertexKHR` (and, for these reads, no `BaryCoordKHR`) is used: every VS `exp paramN`, mesh param and `--mesh-compute` vertex (`tools/mesh_compute_vs.py`) also exports the channel's two f16 halves decoded to f32 (`UnpackHalf2x16`), low halves at location 28 − 2N and high halves at 29 − 2N, so nothing goes above location 29: MoltenVK's `maxVertexOutputComponents` is 124 because Metal counts `gl_Position` in its 128 vertex-output scalars, and the Khronos validation layer counts it too, so a VS output at location 30 failed VUID-RuntimeSpirv-Location-06272 on `vs_ids` (SHADER-291); a PS `*_f16` read of attrN.c takes component c of that ordinary smooth input, then p2 clamps and narrows as before. Interpolation is linear, so the device interpolating the decoded halves gives the same P0 + i(P1 − P0) + j(P2 − P0) as the per-vertex path, with the interpolator's rounding instead of explicit f32 arithmetic. f32 and `v_interp_mov_f32` reads of such a location are the raw word as on any location (flat = the provoking vertex's word, exact). A producer leaves out the halves of a param whose locations would land on one of its own params (params 0..P−1 leave room for the halves of params 0..(28 − P) / 2), and when a PS's canonical decoded-half locations collide with an attribute it reads, its halves are packed into free locations instead (dynamic packing, below). The index records `f16_halves` ({param: [low, high location]}) on both sides; a pipeline links when the PS's entries are among its producer's. Chosen like the wave64 mode: `tools/vk_subgroup_info.py` reports `per_vertex_inputs` (false without `fragmentShaderBarycentric` or on driver ID MoltenVK), and `make_game.py` and `run_gpu_tests.py` turn the flag on where it is false (`LEONIDA_F16_INTERP_FALLBACK=1`/`0` overrides the runner; `build.py` takes only the variable, since it may run in WSL). Without the flag the translation is unchanged: all 139 GPU-test modules are byte-identical to main's, with and without `--bary-fallback` and with `--mesh-compute --wave64-emulate`, so NVIDIA and AMD keep the exact per-vertex path. Confirmed on an Apple A18 Pro (macOS 26.6.2, MoltenVK 1.4.2): `ps_interp_f16_high` drawn with `vs_f16_pack` passes natively and with wave64 emulation, every one of its 4,096 pixels bit-exact to f16 of the exact u and v in both halves (it failed before at pipeline creation), and `ms_f16_pack` through `--mesh-compute` (`LEONIDA_MESH_COMPUTE=1`) passes too; `tests/semantic/test_f16_interp_fallback.py` checks the PS reads (1.75 and 9.0 from the decoded halves), the VS exports (one-lane interpreter), the overlap rules and the default being unchanged. CPU check (TEST-398, `FallbackStagePair`): with ordinary VS exports at 28 and 29, the PS reads those values (5 and 7 in the test) in place of attr0's decoded halves (2 and 3). Only the PS lists attr0 in `f16_halves`. With param28 as the last export, location 28 carries its ordinary value and location 29 has no VS output. When the last ordinary export is at 27, both stages list the pair and the PS reads 2 and 3. The move from 30 to 29 (SHADER-291) was checked on an Apple M5 (macOS 27.2.1, MoltenVK 1.4.2, Khronos validation layer 1.4.363): over the 170 GPU-test modules `vk_pipeline_check` reported VUID-RuntimeSpirv-Location-06272 on 6 vertex shaders at location 30 and on none at 29; the same 15 modules list `f16_halves` for the same params, `run_gpu_tests.py` gives the same result per test, and `ps_interp_f16_high` reads back byte-identical pixels. **Dynamic packing and per-pipeline PSO linking (SHADER-378):** when a PS's canonical `28 − 2N`/`29 − 2N` slots collide with its raw attributes (266 corpus PS where f16-read attrs reach `n >= 7` and raw attrs reach 12–14, all with `2·\|F\| <= 29 − max`) or fall below 0, `assign_f16_half_locations` in `tools/rdna2spirv.py` packs all `f16_halves` pairs downward from location 29 into locations disjoint from its raw attributes (keeping the canonical slots byte-identical whenever collision-free, and refusing only genuine `> 30` location budget overflows); `tools/mesh_compute_vs.py` adds `pair_f16_halves` and an optional `f16_halves` override to `vs_spvasm`; and at graphics PSO creation `runtime/src/shader_library.h` loads `f16_halves` while `runtime/src/spirv_f16_halves.h` (called from `runtime/shims/d3d12_vulkan_device.cpp`) fast-paths exact matches, relocates PS/VS `Location` decorations when needed, demotes unneeded VS static half outputs to `Private`, and synthesizes `UnpackHalf2x16` half exports before `OpReturn` for params a high-param producer (`param0..15`) could not emit statically. Checked by `tests/semantic/test_f16_interp_fallback.py`, `tests/semantic/test_interp_p1lv_f16.py`, `tests/test_mesh_compute_vs.py`, `runtime/test/shader_library_test.cpp`, `runtime/test/spirv_f16_halves_test.cpp`, and `runtime/test/d3d12_f16_halves_test.cpp` (real Vulkan 1.3 draw on NVIDIA GeForce RTX 4060 Ti, driver 32.0.16.1088, Windows 11: 16-param VS + colliding PS both synthesized and relocated render exact RGBA `(64, 191, 127, 255)`). **Unverified:** a PS whose producer exports more params than leave room for the halves it reads (it reads that producer's param, not halves: the `f16_halves` entries then don't match); devices with fewer than 31 output locations; native MoltenVK validation run on macOS and full-corpus recount under `--f16-interp-fallback` (needs game copy); native `MeshEXT` runtime PSO specialization (mesh PSOs are not on `main` yet); devices with fewer than 124 vertex output components. Combined with `--bary-fallback`'s geometry shader (`tools/rdna2spirv.py` allocates `%bary` outside all occupied read and reserved f16-half slots; covered by `tests/semantic/test_bary_fallback.py`, and all `3/3` whole-corpus shaders combining both draw `11/11` targets bit-exact on an RX 6650 XT). | | `v_fmac_f16`, `v_interp_p2/mov_f32` output modifiers | VOP3 `mul:2`/`mul:4`/`div:2` (applied first) and `clamp` to [0, 1] apply to `v_fmac_f16_e64` (before narrowing to f16, matching `v_fma_f16`, high half preserved) and to `v_interp_p2_f32_e64` / `v_interp_mov_f32_e64` (no-op when no modifier is present). Until 2026-11-22 all three dropped output modifiers. Source: LLVM `llvm/test/MC/AMDGPU/gfx10_asm_vop2.s` (`v_fmac_f16_e64`) and `gfx10_asm_vop3.s` (`v_interp_p2_f32_e64`, `v_interp_mov_f32_e64`). Checked on the CPU by `tests/semantic/test_f16_fma_rounding.py` (`test_fmac_output_modifiers`) and `tests/semantic/test_interp_f32_mods.py`, and on a GPU by `ps_fmac_f16_mods.asm`, `ps_interp_f32_mods.asm` and `ps_interp_mov_mods.asm` (the last two drawn with `vs_interp_consts.asm`, whose params are constant over the triangle; each modifier and the omod-before-clamp order change a word; Tesla V100 (NVIDIA 580.95.05, Linux)). **The hardware ignores the f16 omod in the MODE the translator assumes:** on an RDNA2 iGPU (gfx1036) `mul:2`/`mul:4`/`div:2` change an f16 result (`v_fmac_f16`, `v_add/mul/fma_f16`, `v_cvt_f16_f32`, `v_exp/rcp_f16`) only with IEEE 0 and `denorm_mode_16_64 = 0`, and do nothing with f16 denormals kept; omod comes before clamp, and clamp gives +0 for -0 and, with DX10_CLAMP 1, for a NaN (SHADER-135, docs/shader_validation.md). The translator is not changed yet: which of omod and the kept f16 denormals is wrong for the game is a corpus question. | | `v_fmac_f16`, `v_interp_p2/mov_f32`, and f16 output modifiers | VOP3 `omod` (`[60:59]`) scales the floating-point result by `2`, `4`, or `0.5` before `clamp` (`[0.0, 1.0]`), gated by RDNA2 silicon on **both** `MODE.ieee == 0` and output denorms for the **destination precision** being flushed (`fp32_denorm` for `f32` destinations; `fp16_fp64_denorm` for `f16`/`f64` destinations). Under Leonida's default shader `MODE` (`IEEE=0`, FP32 denorms flushed, FP16/FP64 denorms kept `denorm16_64=3`), `Gen.clamp_mods(..., allow_omod=True)` applies `omod` then `clamp` on `f32` destinations (including `v_interp_p2_f32_e64`, `v_interp_mov_f32_e64`, and `v_cvt_f32_f16`), whereas `Gen.clamp_f16` (`allow_omod=False`) drops `omod` and keeps `clamp` on all `f16`-destination instructions (`v_add/sub/subrev/mul/min/max_f16`, `v_fma/fmac/min3/max3/med3_f16`, unary/transcendental/exponent `*_f16`, `v_cvt_f16_*`, `v_interp_p2_f16`, `v_fma_mixlo/hi_f16`). Hardware-verified on native RDNA2 (`gfx1036`, Windows 11, driver `32.0.21045.29003`, AMD clang `23.0.0git`, wave32 & wave64 parity, ELF binary disassembly confirming non-zero VOP3 `[60:59]` bits emitted, in-wave `v_add_f32_e64 mul:2` witness proving `IEEE=0` active -> `6.0` vs `IEEE=1` -> `3.0`): across all 4 `f16`-destination classes (binary ALU, 3-op ALU, unary/transcendental, and `v_cvt_f16_{f32,u16,i16}`), `mul:2`/`mul:4`/`div:2` are completely ignored under `IEEE=0, denorm16_64=3` while `clamp` still saturates `[0.0, 1.0]`, whereas the `f32`-destination control `v_cvt_f32_f16` scales (`2.0 -> 4.0 / 8.0 / 1.0`); flipping `MODE` to `IEEE=0, denorm16_64=0` (flushed FP16 denorms) re-enables `f16` `omod` scaling (`v_fma_f16 mul:2 -> 6.0`, `v_rcp_f16 mul:2 -> 1.0`, `v_cvt_f16_f32 mul:2 -> 4.0`), confirming the exact hardware gating condition. CPU-checked by `tests/semantic/test_f16_omod_rdna2.py`. **The gate is RDNA2 behaviour, not a general RDNA rule.** `tools/f64_omod_probe.py` (added by this PR) measures the same gate by destination precision on a gfx1036 iGPU (driver `31.0.24002.92`, raw ISA, 175 cases, `mismatches=0`, `wave_diffs=0`): `v_cvt_f64_i32`, `v_cvt_f64_u32`, `v_frexp_mant_f64`, `v_div_fixup_f64` and `v_div_fixup_f16` are f16/binary64 destinations and ignore `mul:2`/`mul:4`/`div:2` under `denorm16_64=3`, while `v_cvt_f32_f64` has binary64 sources and an f32 destination and scales under `denorm16_64=3` whenever `denorm32=0`. And @bunbeans2-arch reported in #4371 that RDNA4 `gfx1201` (RX 9070 XT, Windows driver 26.10.1, where IEEE is fixed on) applies the scaling for all 8 binary64 ops with `denorm16_64=3` kept, `v_add_f64 1.5+1.5 mul:2 = 0x4018000000000000`; that run is quoted from the thread and is not reproduced here. The two readings together are why the translator follows the console's RDNA2 MODEs rather than a hardware-agnostic rule, and why no row here should be read as describing RDNA3 or RDNA4. | -| `v_cvt_f16_f32` output modifiers | VOP3 `clamp` and `mul:2`/`mul:4`/`div:2` apply to the f16 result (Mesa ACO declares the op `dst(F16)`), in the order an RX 6800 (`gfx1030`) and Radeon Graphics (`gfx1036`) apply them: the value is rounded to f16 first, then scaled, then clamped, so in RNE `65520 div:2` is inf, not 32768. The scaling works on the f16 bits (`Gen.f16_omod`): a zero or denormal f16, before or after it, gives +0, inf and NaN pass through, and a finite overflow gives inf (±65504 under MODE toward zero, unmeasured). The scaling works on the f16 bits (`Gen.f16_omod`): a pre-omod zero or denormal f16 (`e == 0`) gives `+0`, `div:2` underflowing an exponent-1 normal (`e == 1`) gives signed zero (`h & 0x8000`, so negative inputs give `-0.0`, which a trailing `clamp` still turns into `+0`), `inf` and `NaN` pass through, and finite `mul:2`/`mul:4` overflow gives `±inf` in RNE or `±65504` under `MODE` toward zero (`FP_ROUND = 3`), where `±65520` / `±FLT_MAX` with `div:2` also round to `±65504` before halving to `±32752`. Until 2026-11-22 both modifiers were dropped; `Gen.f16_omod` also flushed `e == 1 div:2` to `+0` until the `gfx1036` measurement. Sources: [@shelbykb2's RX 6800 words](https://github.com/ItsNotRexed/Leonida/pull/718#issuecomment-7074230544) (gfx1030, not the console's gfx1013): [@shelbykb2's RX 6800 words](https://github.com/ItsNotRexed/Leonida/pull/718#issuecomment-7074230544) (gfx1030, not the console's gfx1013) and `tools/cvt_f16_omod_probe.py` on `gfx1036` (Radeon(TM) Graphics, Windows 11 driver `32.0.21045.29003`, wave32 & wave64, 2,880 evaluations, 0 diffs across static/dynamic `MODE`): `clamp` applies in every float mode, the omod only with IEEE off and f16 denormals flushed (with `denorm16_64=3` or `ieee=1` omod is ignored while `clamp` still applies), which is the mode a compiler emits an omod for, as the f32 rows above argue; 2^-15 `mul:2` and -0 `mul:2` gave 0x0000 there. That flush is modelled only on results that carry an omod. The f16 ALU results (`v_fma_f16`, `v_fmac_f16`, …) still scale before narrowing, which differs from this only on overflow, denormals and the sign of zero. Checked by `ps_outmods_f16.asm` (`tests/semantic/test_value_semantics.py`, and on a GPU in both runners): each of its six results changes a word when its modifier is dropped, and two words change when the omod is applied before the rounding. Checked by `ps_outmods_f16.asm` (`tests/semantic/test_value_semantics.py`, and on a GPU in both runners), `tests/test_cvt_f16_omod_probe.py`, and `tests/semantic/test_cvt_f16_omod.py`. | +| `v_cvt_f16_f32` output modifiers | VOP3 `clamp` and `mul:2`/`mul:4`/`div:2` apply to the f16 result (Mesa ACO declares the op `dst(F16)`), in the order an RX 6800 (`gfx1030`) and Radeon Graphics (`gfx1036`) apply them: the value is rounded to f16 first, then scaled, then clamped, so in RNE `65520 div:2` is inf, not 32768. The scaling works on the f16 bits (`Gen.f16_omod`): a zero or denormal f16, before or after it, gives +0, inf and NaN pass through, and a finite overflow gives inf (±65504 under MODE toward zero, unmeasured). The scaling works on the f16 bits (`Gen.f16_omod`): a pre-omod zero or denormal f16 (`e == 0`) gives `+0`, `div:2` underflowing an exponent-1 normal (`e == 1`) gives signed zero (`h & 0x8000`, so negative inputs give `-0.0`, which a trailing `clamp` still turns into `+0`), `inf` and `NaN` pass through, and finite `mul:2`/`mul:4` overflow gives `±inf` in RNE or `±65504` under `MODE` toward zero (`FP_ROUND = 3`), where `±65520` / `±FLT_MAX` with `div:2` also round to `±65504` before halving to `±32752`. Until 2026-11-22 both modifiers were dropped; `Gen.f16_omod` also flushed `e == 1 div:2` to `+0` until the `gfx1036` measurement. Sources: [@shelbykb2's RX 6800 words](https://github.com/ItsNotRexed/Leonida/pull/718#issuecomment-7074230544) (gfx1030, not the console's gfx1013): [@shelbykb2's RX 6800 words](https://github.com/ItsNotRexed/Leonida/pull/718#issuecomment-7074230544) (gfx1030, not the console's gfx1013) and `tools/cvt_f16_omod_probe.py` on `gfx1036` (Radeon(TM) Graphics, Windows 11 driver `32.0.21045.29003`, wave32 & wave64, 2,880 evaluations, 0 diffs across static/dynamic `MODE`): `clamp` applies in every float mode, the omod only with IEEE off and f16 denormals flushed (with `denorm16_64=3` or `ieee=1` omod is ignored while `clamp` still applies), which is the mode a compiler emits an omod for, as the f32 rows above argue; 2^-15 `mul:2` and -0 `mul:2` gave 0x0000 there. That flush is modelled only on results that carry an omod. The f16 ALU results (`v_fma_f16`, `v_fmac_f16`, …) still scale before narrowing, which differs from this only on overflow, denormals and the sign of zero. Checked by `ps_outmods_f16.asm` (`tests/semantic/test_value_semantics.py`, and on a GPU in both runners): each of its six results changes a word when its modifier is dropped, and two words change when the omod is applied before the rounding. Checked by `ps_outmods_f16.asm` (`tests/semantic/test_value_semantics.py`, and on a GPU in both runners), `tests/test_cvt_f16_omod_probe.py`, and `tests/semantic/test_cvt_f16_omod.py`. The DX10 clamp operates on the rounded f16 word, preserving positive subnormals and mapping negative values and NaNs to +0. The same bit clamp is used by `v_div_fixup_f16`. The synthetic Vulkan fixture `cs_w32_cvt_f16_mods.asm` checks both clamp paths and f16-to-f32 conversion of SDWA subnormals and NaNs. | | 16-bit vector compare `op_sel` (`v_cmp(x)_*_{f16,u16,i16}`) | VOP3 `op_sel:[s0,s1]` selects bit `[15:0]` (`0`) or `[31:16]` (`1`) of each source before f16 input modifiers (`neg`/`abs`, via `Gen.f16_in`) or `u16`/`i16` zero-/sign-extension (`OpBitFieldUExtract`/`OpBitFieldSExtract` at bit offset 16 when set, 0 otherwise); VOPC writes a scalar lane mask (VCC/SGPR or EXEC for `v_cmpx`), so there is no destination `op_sel` bit. Measured (TEST-650) with `tools/vcmp16_opsel_probe.py --oracle hw`, which writes `v_cmp_{lt,eq,gt}_{f16,u16,i16}_e64` as raw words with OPSEL set by hand in word 0 [12:11]: llvm-mc rejects `op_sel` on these compares and drops the bits when disassembling, so no listing carries it. On an RDNA2 iGPU (gfx1036), with the Windows HIP launcher (AMD 26.10.1) and independently with the Linux DRM launcher (#3329), all 50 rows read the low halves in wave32 and wave64, including the 20 where the selected halves would answer differently (f16 with and without `neg`, u16, sign-extended i16). The same hand-set bits on `v_add_nc_u16_e64` do select the high halves, so the encoding is right. The translator still honours `op_sel` here (from the ISA text and Mesa ACO `can_use_opsel`), which only a hand-encoded word can reach: #3487, which made it read the low halves as TEST-650 measured, was reverted because the constant, literal and SGPR-high-half checks below (row 403, measured natively) expect `op_sel` to select; the two measurements disagree and are open. Until 2026-11-22 `Gen.compare` hardcoded the low half and ignored `mods`. Source: AMD RDNA2 ISA VOP3 `op_sel` and Mesa ACO `can_use_opsel`. **Measured natively on RDNA2** (gfx1036, AMD Ryzen 7000 iGPU, driver 26.11.2) across wave32 and wave64: `v_cmp` writes 0 for inactive lanes in `sdst` (`s4` in wave32, `s[4:5]` in wave64); `v_cmpx` kills inactive lanes in EXEC; inline float constants (`1.0`, `-2.0`, `0.5`, `4.0`) read f16 in low half with `op_sel=0` and +0.0 with `op_sel=1`; inline integer constants (`1`, `-1`) read low half with `op_sel=0` and high half with `op_sel=1` (`0` for `1`, `0xFFFF` for `-1`); 32-bit literals read `[15:0]` (`op_sel=0`) and `[31:16]` (`op_sel=1`, including signed negative high halves in `i16`); SGPR high halves as src0 and src1 with modifiers (`neg`, `abs`); and f16 ordered vs unordered relations on `qNaN`/`sNaN`. Probed natively with zero divergences by `tools/probe_gfx1036_vcmp16.py`, and checked on the CPU by `tests/semantic/test_vcmp16_opsel.py` (all four `op_sel` combinations, spirv-val compliance, wave32/wave64 EXEC updates and inactive-lane 0 writes in `sdst`). Checked on the CPU by `tests/semantic/test_vcmp16_opsel.py` (all four `op_sel` combinations across `f16` relations/ordered/unordered/NaN/`neg`/`abs`, `u16`, signed `i16`, and `v_cmpx` wave32/wave64 EXEC updates via `spirv_mini_interp` and `spirv_wave_interp`); Not measured: `v_cmpx`, `abs`, RDNA1. **not GPU-verified**. | | `v_cmp_class_f16`, `v_cmpx_class_f16`, `v_cmp_class_f64`, `v_cmpx_class_f64` | IEEE-754 floating-point class tests against the 10-bit class mask (`0: sNaN, 1: qNaN, 2: -inf, 3: -normal, 4: -denormal, 5: -0, 6: +0, 7: +denormal, 8: +normal, 9: +inf`), writing VCC/SGPR or narrowing EXEC (`v_cmpx`). Computed bit-exactly on integer words (so `sNaN` is never quieted by float ops and `v_cmp(x)_class_f64` does not require `OpCapability Float64`): `f16` reads both the value operand (`op_sel[0]`) and the class mask operand via `src_h` (so float inline constants like `0.5`, `1.0`, `-2.0`, `0.15915494` take their 16-bit binary16 value over a zero high half before SDWA selection, matching `tools/sdwa_diff.py --oracle hw` on RDNA2 `gfx1036`; until 2026-11-23 `cmp_class` read the mask with `src_u`, turning inline float constants into 32-bit binary32 bits and failing `sdwa_diff --ops v_cmp_class_f16` 12/500) and applies `abs`/`neg` on bits `[15:0]`; `f16` reads the selected half (`op_sel[0]`, inline f16 constants via `src_h`) and applies `abs`/`neg` on bits `[15:0]`; `f64` reads the `(lo, hi)` pair (32-bit literals placed in the upper word with `lo = 0` per RDNA2 ISA) and applies `abs`/`neg` on `hi`. Output modifiers (`clamp`, `mul:*`, `div:*`) and unsupported `op_sel` bits raise `Unsupported`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (VOPC `V_CMP_CLASS_F16/F64`, `V_CMPX_CLASS_F16/F64`). Checked bit-for-bit across all 10 classes on the CPU (`spirv_mini_interp`) and with `spirv-val` by `tests/semantic/test_alu_cmp_class_f16_f64.py`, and across 500 SDWA programs (`v_cmp_class_f16`, 0 mismatches) via `tools/sdwa_diff.py`; **not GPU-verified** and not run on the shader corpus. . **Hardware-measured natively on `gfx1100`** (RX 7900 XTX, driver 26.10.1) with `tools/hw_oracle`, 85 cases, all matching the operand's own bits: the ten classes on ten `f16` words (`0x7c01` sNaN, `0x7e00` qNaN, `0xfc00` -inf, `0xbc00` -normal, `0x8001` -denormal, `0x8000` -0, `0x0000` +0, `0x0001` +denormal, `0x3c00` +normal, `0x7c00` +inf) and on ten `f64` pairs, each against its own class bit, all ten bits, no bits and the nine other bits (80), plus both `v_cmpx` forms on the launched lane (5). Not measured: `abs`/`neg`/`op_sel`, an inactive lane's `vdst`/`EXEC` under `v_cmpx`, wave64, and the shader corpus. | | Float-to-byte pack | `v_cvt_pk_u8_f32` rounds to nearest even (the default MODE round mode; the hardware follows the MODE register's f32 round mode, which the translator ignores, see #358), clamps to [0, 255], and gives 0 for NaN and negative values, then inserts the byte at `src1[1:0]` of `src2` and keeps the other three. NaN is replaced by +0 before `FClamp`, which is undefined for a NaN operand. **Measured natively** on RDNA2 (gfx1036, the Ryzen 7 9800X3D iGPU, AMD driver 25.10, the instruction run through inline assembly): all 256 inputs k + 0.5 round to even, 0.5 gives 0, 0x3f000001 gives 1, +inf and 300.0 give 255, -inf, -1.0, ±0, denormals and quiet, signalling and negative NaNs give 0 (#358). `cs_cvt_pk_u8.asm` holds eight of these words, checked by `check.py`/`run_gpu_tests.py` and bit-for-bit by `tests/semantic/test_cvt_pk_u8.py`. | diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py index 987a4eb530..e6e1122f3f 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py @@ -104,7 +104,9 @@ def not_found_message(build, missing): CS_SMEM = [0x5eed0024, 0x5eed0028, 0x5eed002c, 0x5eed0030, 0x5eed0010, 0x5eed0014, 0x5eed0018, 0x5eed001c] # -0, and NaN checks that need SignedZeroInfNanPreserve (cs_signed_zero_nan.asm); 0 in out[4..7] means it's missing SIGNED_ZERO_NAN = [0x80000000, 0x80000000, 0x80008000, 0x00008000, 1, 1, 1, 0x00007c00] +CVT_F16_MODS_WORDS = [0xFFC4A000, 0x33800000, 0x36800000, 0xAAAA0001, 0xAAAA03FF, 0xAAAA0000, 0xAAAA0000, 0xAAAA0001] WAVE32_DUMPS = ("cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_wqm_w32", "cs_w32_lane_wrap", "cs_movrelsd_2", "cs_w32_permute", + "cs_w32_cvt_f16_mods", "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop", "cs_w32_lds_u8_d16", "cs_bpermute32", "cs_w32_lds_subdword", "cs_w32_lds_wide", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_exec_const", "cs_w32_mask_imm", "cs_w32_int_ext", @@ -117,6 +119,7 @@ def not_found_message(build, missing): # otherwise pick a narrower size and return different words (#774). WAVE32_LANE_ENV = {"VKC_SUBGROUP_SIZE": "32"} WAVE32_LANE_DUMPS = ("cs_wqm_w32", "cs_w32_lane_wrap", "cs_w32_permute", "cs_bpermute32", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_exec_const", + "cs_w32_cvt_f16_mods", "cs_w32_mask_imm", "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_wrxchg2_ext", "cs_w32_wrxchg2st64", "cs_w32_andn2_exec", "cs_mask_vgpr_exec", "cs_w32_permlane_fi", "cs_w32_exec_computed") CS_DPP = [("cs_dpp", [1, 0, 3, 2, 5, 4, 7, 6]), @@ -134,6 +137,7 @@ def not_found_message(build, missing): WAVE32_DUMPS += tuple(n for n, _ in CS_DPP) WAVE32_LANE_DUMPS += tuple(n for n, _ in CS_DPP) CS_DUMPS = [*CS_DPP, ("cs_smem_vcc_base", CS_SMEM_VCC), ("cs_store", CS_STORE), ("cs_smem_soffset_imm", CS_SMEM), + ("cs_w32_cvt_f16_mods", CVT_F16_MODS_WORDS), # SHADER-52: wave32 lane select is & 31; lane 40 wraps to 8 ("cs_w32_lane_wrap", [25, 16, 777, 777]), # v_movrelsd_2_b32: VGPR[D + M0[25:16]] = VGPR[S0 + M0[9:0]] diff --git a/runtime/test/shaders/cs_w32_cvt_f16_mods.asm b/runtime/test/shaders/cs_w32_cvt_f16_mods.asm new file mode 100644 index 0000000000..c3a3f44742 --- /dev/null +++ b/runtime/test/shaders/cs_w32_cvt_f16_mods.asm @@ -0,0 +1,44 @@ +; f16 conversion and DX10 clamp regressions. Mix VGPR inputs with the local lane ID so the shader +; converts runtime values. Lane 0 stores the eight words for vk_compute_test's dump mode. +; out[0] = 0xffc4a000: DPP fetches lane 1's 0x7e25, widens the NaN and negates its sign +; out[1] = 0x33800000: widen BYTE_1 of 0x00000100 (2^-24) +; out[2] = 0x36800000: widen BYTE_1 of inline f16 2.0 (0x4000 -> 0x0040) +; out[3] = 0xaaaa0001: narrow and clamp 2^-24, keeping the destination's high half +; out[4] = 0xaaaa03ff: narrow and clamp the largest positive f16 subnormal +; out[5] = 0xaaaa0000: div:2 flushes the half result of 2^-14 before clamp +; out[6] = 0xaaaa0000: narrow and clamp -0.0 +; out[7] = 0xaaaa0001: clamp the subnormal quotient of a normal division fixup +; group: 32,1,1 +; mattr: +wavefrontsize32,-wavefrontsize64 +v_xor_b32_e32 v1, 0x7e24, v0 +v_cvt_f32_f16_dpp v8, -v1 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf bound_ctrl:1 +v_xor_b32_e32 v1, 0x0100, v0 +v_cvt_f32_f16_sdwa v9, v1 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_1 +v_cvt_f32_f16_sdwa v10, 2.0 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_1 +v_xor_b32_e32 v2, 0x33800000, v0 +v_xor_b32_e32 v3, 0x387fc000, v0 +v_xor_b32_e32 v4, 0x38800000, v0 +v_xor_b32_e32 v5, 0x80000000, v0 +v_mov_b32_e32 v11, 0xaaaa5555 +v_mov_b32_e32 v12, v11 +v_mov_b32_e32 v13, v11 +v_mov_b32_e32 v14, v11 +v_mov_b32_e32 v15, v11 +v_cvt_f16_f32_e64 v11, v2 clamp +v_cvt_f16_f32_e64 v12, v3 clamp +v_cvt_f16_f32_e64 v13, v4 clamp div:2 +v_cvt_f16_f32_e64 v14, v5 clamp +v_xor_b32_e32 v6, 1, v0 +v_mov_b32_e32 v7, 0x3c00 +v_div_fixup_f16 v15, v6, v7, v7 clamp +v_cmpx_eq_u32_e32 0, v0 +v_mov_b32_e32 v16, 0 +buffer_store_dword v8, v16, s[0:3], 0 offen offset:0 +buffer_store_dword v9, v16, s[0:3], 0 offen offset:4 +buffer_store_dword v10, v16, s[0:3], 0 offen offset:8 +buffer_store_dword v11, v16, s[0:3], 0 offen offset:12 +buffer_store_dword v12, v16, s[0:3], 0 offen offset:16 +buffer_store_dword v13, v16, s[0:3], 0 offen offset:20 +buffer_store_dword v14, v16, s[0:3], 0 offen offset:24 +buffer_store_dword v15, v16, s[0:3], 0 offen offset:28 +s_endpgm diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index 60e9687830..b5f4dd182b 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -37,6 +37,7 @@ from check import IMAGE_STORE_CASES, texture_uav_test from check import salu_ext_test # 38 scalar ALU ops on operands seeded through VKC_SGPRS from check import HEAP_INIT_EXPECTED, heap_init_env # cs_heap_init: vk_compute_test's VKC_HEAP_INIT +from check import CVT_F16_MODS_WORDS from check import shift64_test # dynamic 64-bit vector shifts and overlapping destinations from check import cmp_f64_test # the 32 binary64 vector compares on memory-fed operands from check import round_f64_test # the four binary64 roundings on memory-fed inputs @@ -1204,7 +1205,7 @@ def run_suite(a, work: str) -> int: # With LEONIDA_W64_EMULATE=1 it was translated with --wave64-emulate and runs on any subgroup size. results.append((name,) + wavemask_check(vk_compute, spv, cs_env, w64_emulated())) elif name in ("cs_smem_vcc_base", "cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_w32_lane_wrap", "cs_movrelsd_2", "cs_w32_permute", "cs_w32_sincos", "cs_w32_buffer_sub16", "cs_w32_buffer_store_sub", "cs_w32_fcmpswap", "cs_w32_permlane_fi", "cs_exec_const", "cs_w32_mask_imm", "cs_w64_mask_imm", "cs_w32_lds_u8_d16", "cs_w32_lds_subdword", "cs_w32_lds_wide", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_wave64_ballot", "cs_wm_half_ops", "cs_wm_half_cmp", "cs_wm_bfm64", "cs_wm_scc_rfl", "cs_wqm_w64", "cs_wqm_w32", "cs_wqm_w64_half", - "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", "cs_dpp_ops", "cs_dpp_bank", "cs_dpp_fi", + "cs_w32_cvt_f16_mods", "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", "cs_dpp_ops", "cs_dpp_bank", "cs_dpp_fi", "cs_dpp_bound", "cs_dpp_cmp", "cs_dpp_cmpx", "cs_dpp_w64", "cs_w64_mask_detect", "cs_w64x_readlane", "cs_w64x_writelane", "cs_w64x_readfirstlane", "cs_w64x_bpermute", "cs_w64x_permute", @@ -1238,6 +1239,7 @@ def run_suite(a, work: str) -> int: # ds_cmpst_f32 and buffer_atomic_fcmpswap: float compare (cs_w32_fcmpswap.asm) "cs_w32_fcmpswap": [0, 0x3F800000, 0x7FC00000, 0x3F800000, 0x80000000, 0x40400000, 0x3F800000, 0x7FC00000], "cs_w32_new_ops": [0x55, 0x8001, 0xC0000000, 0x80014000, 0x4000FFFF, 0x77, 0x99, 0x1234], + "cs_w32_cvt_f16_mods": CVT_F16_MODS_WORDS, "cs_w32_misc_ext": [0x0FFF0FFF, 0xE2C4A688, 0x0007FFFF, 0x7FFF8000, 0xFFFE0002, 0xFFFF0005, 0x509, 0xCAFEF00D], "cs_w32_salu64": [0x1E6A2C48, 0x1234, 0xFFFFFFFF, 0x100, 47, 48, 0xFFFF8000, 0xFFFFFFFE], # SHADER-85: ds_read_u8/i8_d16[_hi] (cs_w32_lds_u8_d16.asm header) @@ -1336,7 +1338,8 @@ def run_suite(a, work: str) -> int: want = cs_dump_wants[name] # Every dump but cs_store / cs_smem_soffset_imm / cs_w32_lane_wrap / cs_movrelsd_2 / cs_w32_permute / # cs_w32_lds_u8_d16 / cs_w32_sincos / cs_w32_int_ext / cs_w32_salu64 / cs_w32_misc_ext / cs_w32_new_ops / cs_signed_zero_nan, the wave32 - # cs_wqm_w32 / cs_bpermute32 and the DPP tests is a whole-wave (wave64) mask test: ask for a 64-wide subgroup and skip, + # cs_w32_cvt_f16_mods / cs_wqm_w32 / cs_bpermute32 and the DPP tests is a whole-wave (wave64) mask test: + # ask for a 64-wide subgroup and skip, # as check.py does, where the device has none # (vk_compute_test exits 77) instead of reporting a failure. With LEONIDA_W64_EMULATE=1 they were # translated with --wave64-emulate and run on any subgroup size. @@ -1348,7 +1351,7 @@ def run_suite(a, work: str) -> int: partial = name in ("cs_w64x_partial", "cs_w64x_partial_scmp", "cs_w64x_partial_swizzle") wave64 = name not in ("cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_wqm_w32", "cs_w32_lane_wrap", "cs_movrelsd_2", "cs_w32_permute", "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop", - "cs_w32_lds_u8_d16", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", + "cs_w32_lds_u8_d16", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_w32_cvt_f16_mods", "cs_w32_lds_subdword", "cs_w32_lds_wide", "cs_bpermute32", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_w32_permlane_fi", "cs_w32_sincos", "cs_w32_buffer_sub16", "cs_w32_buffer_store_sub", "cs_w32_fcmpswap", "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_wrxchg2_ext", "cs_w32_wrxchg2st64", "cs_exec_const", "cs_w32_mask_imm", "cs_mask_vgpr_exec", diff --git a/tests/semantic/test_cvt_f16_denorm_mods.py b/tests/semantic/test_cvt_f16_denorm_mods.py new file mode 100644 index 0000000000..99d353cb3a --- /dev/null +++ b/tests/semantic/test_cvt_f16_denorm_mods.py @@ -0,0 +1,183 @@ +"""Synthetic conversion, subnormal, and clamp tests for RDNA2 binary16 VALU instructions.""" + +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import patch + +sys.dont_write_bytecode = True +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import support +import spirv_asm +import spirv_mini_interp as si + + +HALF_TO_FLOAT = si.half_to_float + + +def conversion_fragment(op, cases): + """Each case supplies a VGPR word and an operand string with {src} naming that VGPR.""" + lines = [] + for i, (word, operands) in enumerate(cases): + src = f"v{i + 8}" + lines.extend([f"v_mov_b32 {src}, {word:#x}", f"v_mov_b32 v{i}, 0xaaaa5555", + f"{op} v{i}, {operands.format(src=src)}"]) + lines += ["exp mrt0 v0, v1, v2, v3 done vm", "s_endpgm"] + return support.translate_lines("ps_cvt_f16_denorm_mods", lines) + + +def flushed_unpack(word): + """Model a driver's legal UnpackHalf2x16 choice of flushing binary16 subnormals.""" + half = word & 0xFFFF + if 0 < (half & 0x7FFF) < 0x0400: + half &= 0x8000 + return HALF_TO_FLOAT(half) + +SDWA_WIDEN = "dst_sel:DWORD dst_unused:UNUSED_PAD" +SDWA_CASES = [ + (0xDEAD0001, "{src} " + SDWA_WIDEN + " src0_sel:BYTE_0"), + (0xDEAD0100, "{src} " + SDWA_WIDEN + " src0_sel:BYTE_1"), + (0x80013C00, "|{src}| " + SDWA_WIDEN + " src0_sel:WORD_1"), + (0, "2.0 " + SDWA_WIDEN + " src0_sel:BYTE_1"), +] +NARROW_CLAMP_CASES = [ + (0x33800000, "{src} clamp"), # smallest positive subnormal + (0x387FC000, "{src} clamp"), # largest positive subnormal + (0x80000000, "{src} clamp"), # -0 saturates to +0 + (0x7FA02000, "{src} clamp"), # DX10 clamp maps NaN to +0 +] +DPP_LINES = [ + "v_mbcnt_lo_u32_b32 v0, -1, 0", + "v_xor_b32 v1, 1, v0", + "v_mov_b32 v2, 0xdeadbeef", + "v_mov_b32 v3, 0xaaaa5555", + "s_mov_b32 exec_lo, 13", # lanes 0, 2, 3 + "v_cvt_f32_f16_dpp v2, -v1 quad_perm:[2,3,0,1] row_mask:0xf bank_mask:0xf bound_ctrl:1", + "v_cvt_f16_f32_e64 v3, 0x33800000 clamp", + "s_mov_b32 exec_lo, -1", + "v_mov_b32 v4, 0", + "exp pos0 v4, v4, v4, v4 done", + "exp param0 v2, v3, v4, v4", + "s_endpgm", +] + + +class CvtF16DenormModsTests(unittest.TestCase): + def test_widen_finite_values_and_signed_zero(self): + spv = conversion_fragment("v_cvt_f32_f16_e64", [ + (0xAAAA3E00, "{src}"), (0xAAAA0000, "-{src}"), + (0xAAAA8000, "{src}"), (0xAAAA8000, "|{src}|"), + ]) + self.assertEqual(support.mrt0_words(spv), [0x3FC00000, 0x80000000, 0x80000000, 0]) + + def test_widen_subnormals_even_if_unpack_flushes_them(self): + spv = conversion_fragment("v_cvt_f32_f16_e64", [ + (0x0001, "{src}"), (0x03FF, "{src}"), (0x8001, "{src}"), (0x8001, "-|{src}|"), + ]) + with patch.object(si, "half_to_float", flushed_unpack): + self.assertEqual(support.mrt0_words(spv), [0x33800000, 0x387FC000, 0xB3800000, 0xB3800000]) + + def test_widen_sdwa_before_modifiers_and_inline_float(self): + spv = conversion_fragment("v_cvt_f32_f16_sdwa", SDWA_CASES) + with patch.object(si, "half_to_float", flushed_unpack): + self.assertEqual(support.mrt0_words(spv), [0x33800000, 0x33800000, 0x33800000, 0x36800000]) + + def test_widen_nan_payload_sign_and_source_modifiers(self): + spv = conversion_fragment("v_cvt_f32_f16_e64", [ + (0xFC01, "{src}"), (0xFE25, "-{src} mul:2"), + (0xFE25, "|{src}|"), (0xFE25, "-|{src}|"), + ]) + self.assertEqual(support.mrt0_words(spv), [0xFF802000, 0x7FC4A000, 0x7FC4A000, 0xFFC4A000]) + + def test_widen_clamp_and_infinities(self): + spv = conversion_fragment("v_cvt_f32_f16_e64", [ + (0x7C00, "{src}"), (0xFC00, "{src}"), (0x7E25, "{src} clamp"), (0xFC00, "{src} clamp"), + ]) + self.assertEqual(support.mrt0_words(spv), [0x7F800000, 0xFF800000, 0, 0]) + + def test_widen_omod_precedes_clamp(self): + spv = conversion_fragment("v_cvt_f32_f16_e64", [ + (0x3A00, "{src} clamp mul:2"), (0, "0.5 mul:4"), + (0x0001, "{src} div:2"), (0x8001, "-|{src}| clamp mul:4"), + ]) + self.assertEqual(support.mrt0_words(spv), [0x3F800000, 0x40000000, 0x33000000, 0]) + + def test_dpp_selects_before_modifiers_and_keeps_inactive_lanes(self): + spv = support.translate_lines("vs_cvt_f16_dpp", DPP_LINES) + _, outputs = si.run_workgroup(spv, 32, 32, inputs_for=lambda lane: {"%sg_lane": lane}, return_outputs=True) + words = [tuple(out["%out_param0"][:2]) for out in outputs] + self.assertEqual(words[:4], [(0xB4400000, 0xAAAA0001), (0xDEADBEEF, 0xAAAA5555), + (0xB3800000, 0xAAAA0001), (0x80000000, 0xAAAA0001)]) + + def test_narrow_rounds_to_even_and_keeps_high_half(self): + spv = conversion_fragment("v_cvt_f16_f32_e64", [ + (0x3F801000, "{src}"), (0x3F801001, "{src}"), + (0x33C00000, "{src}"), (0x477FF000, "{src}"), + ]) + self.assertEqual(support.mrt0_words(spv), [0xAAAA3C00, 0xAAAA3C01, 0xAAAA0002, 0xAAAA7C00]) + + def test_narrow_clamp_keeps_positive_subnormal_bits(self): + spv = conversion_fragment("v_cvt_f16_f32_e64", NARROW_CLAMP_CASES) + self.assertNotIn("UnpackHalf2x16", spv) + self.assertEqual(support.mrt0_words(spv), [0xAAAA0001, 0xAAAA03FF, 0xAAAA0000, 0xAAAA0000]) + + def test_narrow_omod_runs_on_the_half_before_clamp(self): + spv = conversion_fragment("v_cvt_f16_f32_e64", [ + (0x3E800000, "{src} mul:2"), (0x3F400000, "{src} clamp mul:4"), + (0x3F400000, "{src} clamp div:2"), (0x38800000, "{src} clamp div:2"), + ]) + self.assertEqual(support.mrt0_words(spv), [0xAAAA3800, 0xAAAA3C00, 0xAAAA3600, 0xAAAA0000]) + + def test_narrow_sdwa_clamps_before_merging_the_destination(self): + keep = "clamp dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:DWORD" + spv = conversion_fragment("v_cvt_f16_f32_sdwa", [ + (0x33800000, "{src} " + keep), (0xC0000000, "{src} " + keep), + (0x40000000, "{src} " + keep), (0x7FC00000, "{src} " + keep), + ]) + self.assertEqual(support.mrt0_words(spv), [0x00015555, 0x00005555, 0x3C005555, 0x00005555]) + + def test_div_fixup_clamps_the_half_before_writing_it(self): + spv = support.translate_lines("ps_div_fixup_f16_bit_clamp", [ + "v_mov_b32 v0, 0xaaaa5555", "v_mov_b32 v1, v0", "v_mov_b32 v2, v0", "v_mov_b32 v3, v0", + "v_mov_b32 v8, 0x03ff0001", "v_mov_b32 v9, 0x3c00", "v_mov_b32 v10, 0xbc00", + "v_div_fixup_f16 v0, v8, v9, v9 clamp", + "v_div_fixup_f16 v1, v8, v9, v9 op_sel:[1,0,0,1] clamp", + "v_div_fixup_f16 v2, v8, v9, v10 clamp", + "v_div_fixup_f16 v3, 0, v9, v10 clamp", + "exp mrt0 v0, v1, v2, v3 done vm", "s_endpgm", + ]) + self.assertNotIn("UnpackHalf2x16", spv) + self.assertEqual(support.mrt0_words(spv), [0xAAAA0001, 0x03FF5555, 0xAAAA0000, 0xAAAA0000]) + + @unittest.skipUnless(shutil.which("spirv-val"), "spirv-val not installed") + def test_spirv_validation_with_both_assemblers(self): + modules = { + "sdwa": conversion_fragment("v_cvt_f32_f16_sdwa", SDWA_CASES), + "clamp": conversion_fragment("v_cvt_f16_f32_e64", NARROW_CLAMP_CASES), + "dpp": support.translate_lines("vs_cvt_f16_dpp", DPP_LINES), + } + with tempfile.TemporaryDirectory() as tmp: + for name, spv in modules.items(): + binary = Path(tmp, name + ".spv") + for assembler in ("python", "spirv-as"): + with self.subTest(module=name, assembler=assembler): + if assembler == "python": + binary.write_bytes(spirv_asm.assemble(spv)) + elif shutil.which(assembler): + made = subprocess.run([assembler, "-", "--target-env", "vulkan1.2", "-o", str(binary)], + input=spv, capture_output=True, text=True) + self.assertEqual(made.returncode, 0, made.stderr) + else: + self.skipTest("spirv-as not installed") + checked = subprocess.run(["spirv-val", "--target-env", "vulkan1.2", str(binary)], + capture_output=True, text=True) + self.assertEqual(checked.returncode, 0, checked.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index b10de728ec..096a3e710c 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -6985,6 +6985,15 @@ def clamp_f16(self, v, mods): # f16 destination under default MODE (denorm16_64=3): omod ignored by silicon, clamp kept. return self.clamp_mods(v, mods, allow_omod=False) + def clamp_f16_bits(self, h): + """Apply DX10 clamp to an already rounded half in the low 16 bits of a %uint.""" + zero, capped, out = self.tmp(), self.tmp(), self.tmp() + # As unsigned words, all negative halves (including -0) and all positive NaNs exceed +inf. + self.emit(f"{zero} = OpUGreaterThan %bool {h} {self.cu(0x7C00)}") + self.emit(f"{capped} = OpExtInst %uint %glsl UMin {h} {self.cu(0x3C00)}") + self.emit(f"{out} = OpSelect %uint {zero} {self.cu(0)} {capped}") + return out + def _validate_unary_f16(self, op, raw_op, a, mods): """Validate operands, encoding suffix, and modifiers for unary f16 VOP1/VOP3/SDWA ops.""" if len(a) != 2: @@ -7825,13 +7834,16 @@ def selectors(key, count, limit): zero = self.cu(0) src0 = self.tmp() self.emit(f"{src0} = OpSelect %uint {src_ok} {shuffled} {zero}") - src0 = self.modify(src0, src) + if base_op(ins["op"]) == "v_cvt_f32_f16": + # Pass the modifiers through the lane select so the conversion applies them to the half source. + args[first] = {**src, "k": "ssa", "v": src0} + else: + args[first] = {"k": "ssa", "v": self.modify(src0, src)} if dpp8 is not None or bound: write = enabled else: write = self.tmp() self.emit(f"{write} = OpLogicalAnd %bool {enabled} {src_ok}") - args[first] = {"k": "ssa", "v": src0} if compare: # Every lane is enabled and an invalid source reads 0 (checked above), so the compare's own EXEC guard # is the only one: the mask write is the plain compare's (for v_cmpx, EXEC's). @@ -8078,10 +8090,7 @@ def _insn(self, ins): x = self.src_f(a[1]) h = self.f16_omod(self.f16_res(x), mods) if "clamp" in mods: - v2, f = self.tmp(), self.tmp() - self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {h}") - self.emit(f"{f} = OpCompositeExtract %float {v2} 0") - h = self.f16_bits(self.clamp_mods(f, ["clamp"])) # exact: the clamped value is an f16 + h = self.clamp_f16_bits(h) self.write_lo16(a[0], h) elif op == "s_mulk_i32": v = a[1]["v"] & 0xFFFF @@ -10535,21 +10544,8 @@ def cls16(w): self.emit(f"{r4} = OpSelect %uint {nan1} {s1} {r3}") self.emit(f"{r5} = OpSelect %uint {nan2} {s2} {r4}") if has_clamp: - v2f, fv = self.tmp(), self.tmp() - self.emit(f"{v2f} = OpExtInst %v2float %glsl UnpackHalf2x16 {r5}") - self.emit(f"{fv} = OpCompositeExtract %float {v2f} 0") - self.f16_out(a[0], self.clamp_f16(fv, mods), dhi) - elif not dhi: - self.write_lo16(a[0], r5) - else: - if a[0]["k"] != "vgpr": - raise Unsupported("op_sel destination") - old, keep, sh16, v = (self.tmp() for _ in range(4)) - self.emit(f"{old} = OpCopyObject %uint {self.load_reg('vgpr', a[0]['r'])}") - self.emit(f"{keep} = OpBitwiseAnd %uint {old} {self.cu(0xFFFF)}") - self.emit(f"{sh16} = OpShiftLeftLogical %uint {r5} {self.cu(16)}") - self.emit(f"{v} = OpBitwiseOr %uint {keep} {sh16}") - self.dst(a[0], v) + r5 = self.clamp_f16_bits(r5) + self.write_half16(a[0], r5, dhi) else: d = a[0] if d["k"] != "vgpr" or d.get("n") != 2: @@ -11385,27 +11381,31 @@ def f64(sv): lo = self.tmp() self.emit(f"{lo} = OpBitwiseAnd %uint {r} {self.cu(0xFFFF)}") if "clamp" in mods and op in ("v_frexp_mant_f16", "v_ldexp_f16"): - s15, e16, frac16, is_exp31, is_nan, is_zero_out, gt_one, c1, clamped_lo = \ - (self.tmp() for _ in range(9)) - self.emit(f"{s15} = OpBitFieldUExtract %uint {lo} {self.cu(15)} {self.cu(1)}") - is_neg = self.tmp_bool_nz(s15) - self.emit(f"{e16} = OpBitFieldUExtract %uint {lo} {self.cu(10)} {self.cu(5)}") - self.emit(f"{is_exp31} = OpIEqual %bool {e16} {self.cu(31)}") - self.emit(f"{frac16} = OpBitwiseAnd %uint {lo} {self.cu(0x3FF)}") - has_frac = self.tmp_bool_nz(frac16) - self.emit(f"{is_nan} = OpLogicalAnd %bool {is_exp31} {has_frac}") - self.emit(f"{is_zero_out} = OpLogicalOr %bool {is_neg} {is_nan}") - self.emit(f"{gt_one} = OpUGreaterThan %bool {lo} {self.cu(0x3C00)}") - self.emit(f"{c1} = OpSelect %uint {gt_one} {self.cu(0x3C00)} {lo}") - self.emit(f"{clamped_lo} = OpSelect %uint {is_zero_out} {self.cu(0)} {c1}") - lo = clamped_lo + lo = self.clamp_f16_bits(lo) self.write_half16(a[0], lo, dhi) elif op == "v_cvt_f32_f16": - u = self.src_h(a[1]) - v2, f = self.tmp(), self.tmp() - self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {u}") - self.emit(f"{f} = OpCompositeExtract %float {v2} 0") - self.dst(a[0], self.tou(self.clamp_mods(self.modify_f(f, a[1]), mods))) + f, h, const_nan = self.f16_in_bits(a[1]) + v = self.tou(self.clamp_mods(f, mods)) + if const_nan is not False: + # Under IEEE=0 the conversion preserves the modified sign and full payload, including the + # quiet bit (tools/f32_fuzz.py). Keep these bits out of the driver's float arithmetic. + nan_bits = self.cu(0) + if "clamp" not in mods: + sign, sign32, mant, mant32, base, nan_bits = (self.tmp() for _ in range(6)) + self.emit(f"{sign} = OpBitwiseAnd %uint {h} {self.cu(0x8000)}") + self.emit(f"{sign32} = OpShiftLeftLogical %uint {sign} {self.cu(16)}") + self.emit(f"{mant} = OpBitwiseAnd %uint {h} {self.cu(0x3FF)}") + self.emit(f"{mant32} = OpShiftLeftLogical %uint {mant} {self.cu(13)}") + self.emit(f"{base} = OpBitwiseOr %uint {sign32} {self.cu(0x7F800000)}") + self.emit(f"{nan_bits} = OpBitwiseOr %uint {base} {mant32}") + if const_nan: + v = nan_bits + else: + is_nan = self._f16_half_nan(h) + out = self.tmp() + self.emit(f"{out} = OpSelect %uint {is_nan} {nan_bits} {v}") + v = out + self.dst(a[0], v) elif op in ("v_interp_p1_f32", "v_interp_p2_f32", "v_interp_mov_f32"): # Single-lane model: the barycentric p1/p2 pair yields the interpolated attribute, and the mov of P0 # the provoking vertex's value. An input only ever read through the mov is declared Flat: such