From 355c8c9c2da01a9898df5061d266ca1f5567cdc9 Mon Sep 17 00:00:00 2001 From: milk4sale <53350507+milk4sale@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:04:58 -0600 Subject: [PATCH 1/3] tests: GPU readback for the binary64 roundings, v_trunc_f64, v_ceil_f64, v_rndne_f64 and v_floor_f64 (GPU-ROUND-F64) The translator gives the four ops to the driver's double-precision Trunc, Ceil, RoundEven and Floor, and no fixture in runtime/test/shaders ran them, so what a driver does with ties, the largest value below 0.5, values at and above 2^52, signed zeros, subnormals, infinities and NaNs had never gone through the GPU suite. cs_w32_round_f64 is memory-fed, like cs_w32_shift64 and cs_w32_cmp_f64: check.py seeds 64 inputs and each thread loads one at run time and stores eight results: the four roundings, v_trunc_f64 with a neg source, v_ceil_f64 with an abs source, a v_floor_f64 whose destination pair overlaps its source pair, and a v_rndne_f64 run with the odd threads turned off, whose destination must keep the pair it held. The expected words come from Python floats (exact IEEE-754, the result keeping its source's sign) and are checked against exact rational rounding in tests/test_gpu_round_f64.py. Two kinds of input are judged by what Vulkan lets a driver do, not by RDNA2: a NaN may come back as another NaN, and a subnormal may be read as a zero of its sign, since the module declares no DenormPreserve for 64 bits. That is what the fixture measured: on an RTX 4070 Ti a signalling NaN comes back quiet, and on llvmpipe the smallest subnormals are also read as zero. The row in docs/design.md records both as an approximation. dump_test takes an optional judge for such a readback. No translator or runtime change. Co-Authored-By: Claude Fable 5.2 --- docs/design.md | 2 +- docs/testing.md | 24 +++ runtime/test/shaders/check.py | 124 ++++++++++- runtime/test/shaders/cs_w32_round_f64.asm | 56 +++++ scripts/run_gpu_tests.py | 5 + tests/test_gpu_round_f64.py | 246 ++++++++++++++++++++++ tests/test_shader_checks.py | 12 +- 7 files changed, 464 insertions(+), 5 deletions(-) create mode 100644 runtime/test/shaders/cs_w32_round_f64.asm create mode 100644 tests/test_gpu_round_f64.py diff --git a/docs/design.md b/docs/design.md index a649f4bf14..d21ee71154 100644 --- a/docs/design.md +++ b/docs/design.md @@ -384,7 +384,7 @@ How the generated SPIR-V expects the runtime to work: | 32-bit integers to binary64 | `v_cvt_f64_i32` sign-extends the input value and `v_cvt_f64_u32` treats it as unsigned. Every 32-bit integer is exactly representable in binary64. The low word goes in the first destination VGPR. **The output scaling is gated by `MODE`, measured by @fiestorra**: on a gfx1036 iGPU (Radeon(TM) Graphics, drivers `31.0.24002.92` and `32.0.21045.29003` (the same counts on both), raw ISA through `tools/hw_oracle`, `tools/f64_omod_probe.py`, 6 inputs x 5 modifier forms x 5 MODEs, wave32 and wave64 identical) `mul:2`/`mul:4`/`div:2` scale the binary64 result only under `IEEE=0` with `denorm_mode_16_64=0`; under `denorm_mode_16_64=3`, which is what the translator assumes, and under `IEEE=1` they are ignored, while `clamp` applies in every MODE — so only `clamp` reaches `dst_f64` for these two ops, as `v_ldexp_f64` already does. For input `0x80000001`, SPIRV-Tools constant folding reproduced both words of each result in the synthetic `ps_int32_to_f64.s` fixture. [AMD RDNA 2 ISA, VOP1 conversions](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) | | `v_add_f64` output modifiers | The double sum is scaled by `mul:2`, `mul:4` or `div:2` if present, then clamped to [0, 1] if `clamp` is set, as for f32 (`clamp_mods_f64`, GLSL.std.450 `FClamp` on the double, so a NaN result and the sign of a -0 result are left to the driver, also as for f32). **Until 2026-11-22 both were ignored.** Source: LLVM AMDGPU defines it as `VOP3Inst<"v_add_f64", VOP3_Profile>` (VOP3Instructions.td), and `VOPProfile` sets `HasClamp` (f64 is a modifier type) and `HasOMod` (floating-point destination) (SIInstrInfo.td). It is the only f64 arithmetic the translator handles; `v_cvt_f32_f64` has the row above. `tests/test_f64_output_modifiers.py` checks the SPIR-V data flow; `runtime/test/shaders/ps_f64_mods.asm` is the GPU test (needs `shaderFloat64`, which `vk_harness` now enables when the fragment shader declares `Float64`), passed on an NVIDIA RTX 6000 Ada (driver 615.71.09, Linux; 4096/4096 pixels exact, and the `main` translator gives the predicted old words). | | `v_rcp_f64`, `v_rsq_f64`, `v_sqrt_f64` | Double-precision reciprocal (`OpFDiv %double 1.0 x`), inverse square root (`GLSL.std.450 InverseSqrt`), and square root (`GLSL.std.450 Sqrt`), requiring `Float64` (`shaderFloat64`). VOP3 input modifiers (`abs`, `neg`) apply to the double operand, and output modifiers (`mul:2`, `mul:4`, `div:2`, then `clamp` to [0, 1]) apply via `clamp_mods_f64` (LLVM `VOP1Inst` / `VOP_F64_F64` in `VOP1Instructions.td`, `HasClamp` and `HasOMod` via `VOPProfile`). Special-value edge cases (`±0`, negative inputs, NaN) follow the driver's SPIR-V `OpFDiv`/`InverseSqrt`/`Sqrt` rules, as for the f32 forms. Checked by `tests/test_f64_transcendentals.py` (SPIR-V data flow and `spirv-val`). **Measured on RDNA2** (gfx1036 iGPU, Windows driver 31.0.24002.92, `tools/hw_oracle` raw kernels, MODE with IEEE on and f64 denormals kept): `v_sqrt_f64` is not the correctly rounded root. `sqrt(4.0)` stored `0x4000000004000000` (2.0000000298), `sqrt(9.0)` `0x4008000004000000`, `sqrt(0.25)` `0x3fe0000004000000` and `sqrt(2.0)` `0x3ff6a09e64000000`. Against the correctly rounded roots, the first three are exactly +2^26 ulps off, and `sqrt(2.0)` is −41,892,813 ulps (about −2^25.3) from `0x3ff6a09e667f3bcd` (1.4142135624), so only about 26 of the 53 significand bits are right. `GLSL.std.450 Sqrt` is the more accurate lowering, and a difference from the instruction on RDNA2 hardware is not a translator bug. `v_rcp_f64` and `v_rsq_f64` returned exact values, but only powers of two were tried, so their accuracy is unmeasured. None of the three occurs in the 26,503 game listings ([measurement](https://github.com/ItsNotRexed/Leonida/issues/4084#issuecomment-7088412190), @fiestorra). | -| `v_trunc_f64`, `v_ceil_f64`, `v_rndne_f64`, `v_floor_f64` | Round binary64 toward zero, positive infinity, nearest-even, or negative infinity respectively; the result stays binary64. The translator maps these to GLSL.std.450 `Trunc`, `Ceil`, `RoundEven`, and `Floor` with `shaderFloat64` (no intermediate f32). Register pairs are low word first, literal dwords fill bits 63:32 with a zero low word, and inactive lanes keep both destination words. VOP3 applies source modifiers before rounding and the existing f64 scale/clamp path afterwards. Sources: AMD [RDNA 2 ISA](https://gpuopen.com/download/rdna2-shader-instruction-set-architecture.pdf) §6.2.1 and §12.8 (VOP1 opcodes 23–26), and LLVM's [GFX10 assembler tests](https://github.com/llvm/llvm-project/blob/1a7ece827ab3543387ee1adf1eb4c8878905b577/llvm/test/MC/AMDGPU/gfx10_asm_vop1.s). Value and SPIR-V checks: `tests/semantic/test_f64_round.py`. Hardware-confirmed natively on RDNA2 (`gfx1036` iGPU, Windows driver 32.0.21042.62, `tools/hw_oracle`, wave32 and wave64 identical on every case) by @timelery: exact IEEE-754 rounding that keeps signed zeros and binary64 subnormals (`ceil(+sub)` = +1.0, `ceil(-sub)` = -0.0, `floor(+sub)` = +0.0, `floor(-sub)` = -1.0, `trunc(±sub)` = ±0.0, `rndne(±0.5)` = ±0.0, `rndne(±1.5)` = ±2.0, `rndne(±2.5)` = ±2.0, ±inf stays ±inf, and ±qNaN/±sNaN pass through unchanged under IEEE=0), where `sub` is the smallest binary64 subnormal; the hex literal dword populates bits 63:32 with a zero low word (`v_floor_f64 v[4:5], 0x3ff80000` -> `0x3ff0000000000000`); and the VOP3 output modifiers behave as for `v_add_f64`/`v_sqrt_f64`: applied on hardware under `denorm16_64=0` and ignored under `denorm16_64=3` (IEEE=0), while the translator applies them through `clamp_mods_f64` as those rows do. | +| `v_trunc_f64`, `v_ceil_f64`, `v_rndne_f64`, `v_floor_f64` | Round binary64 toward zero, positive infinity, nearest-even, or negative infinity respectively; the result stays binary64. The translator maps these to GLSL.std.450 `Trunc`, `Ceil`, `RoundEven`, and `Floor` with `shaderFloat64` (no intermediate f32). Register pairs are low word first, literal dwords fill bits 63:32 with a zero low word, and inactive lanes keep both destination words. VOP3 applies source modifiers before rounding and the existing f64 scale/clamp path afterwards. Sources: AMD [RDNA 2 ISA](https://gpuopen.com/download/rdna2-shader-instruction-set-architecture.pdf) §6.2.1 and §12.8 (VOP1 opcodes 23–26), and LLVM's [GFX10 assembler tests](https://github.com/llvm/llvm-project/blob/1a7ece827ab3543387ee1adf1eb4c8878905b577/llvm/test/MC/AMDGPU/gfx10_asm_vop1.s). Value and SPIR-V checks: `tests/semantic/test_f64_round.py`. Hardware-confirmed natively on RDNA2 (`gfx1036` iGPU, Windows driver 32.0.21042.62, `tools/hw_oracle`, wave32 and wave64 identical on every case) by @timelery: exact IEEE-754 rounding that keeps signed zeros and binary64 subnormals (`ceil(+sub)` = +1.0, `ceil(-sub)` = -0.0, `floor(+sub)` = +0.0, `floor(-sub)` = -1.0, `trunc(±sub)` = ±0.0, `rndne(±0.5)` = ±0.0, `rndne(±1.5)` = ±2.0, `rndne(±2.5)` = ±2.0, ±inf stays ±inf, and ±qNaN/±sNaN pass through unchanged under IEEE=0), where `sub` is the smallest binary64 subnormal; the hex literal dword populates bits 63:32 with a zero low word (`v_floor_f64 v[4:5], 0x3ff80000` -> `0x3ff0000000000000`); and the VOP3 output modifiers behave as for `v_add_f64`/`v_sqrt_f64`: applied on hardware under `denorm16_64=0` and ignored under `denorm16_64=3` (IEEE=0), while the translator applies them through `clamp_mods_f64` as those rows do. GPU-run by `runtime/test/shaders/cs_w32_round_f64.asm` (64 memory-fed inputs through the four ops, `neg` and `abs` sources, a destination pair that overlaps its source, an inactive lane): on an RTX 4070 Ti (NVIDIA 620.70.06, Linux) every result is the hardware's except those of a signalling NaN, which comes back quiet (`0x7ff0000000000001` gives `0x7ff8000000000001`, sign and payload kept), and on llvmpipe (LLVM 23.1.4) the two smallest subnormals are also read as zero (`v_ceil_f64` of the positive one gives +0, not 1), since the module declares no `DenormPreserve` for 64 bits. **Approximation:** for a signalling NaN and, on a driver that flushes them, for a binary64 subnormal, the result is the driver's and not RDNA2's. | | Floating-point class compare | `v_cmp_class_f32` writes the selected class to a lane mask. `v_cmpx_class_f32` intersects the existing EXEC with that same predicate and preserves VCC, as specified in [AMD's RDNA2 ISA §12.9](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf). VOP3 `abs` and `neg` on `src0` are applied as raw sign-bit moves on the 32-bit integer bits (`OpBitwiseAnd 0x7FFFFFFF`, then `OpBitwiseXor 0x80000000`) rather than `FAbs`/`OpFNegate`, so signalling NaNs stay signalling (class bit 0) and subnormals are never flushed. **Hardware-measured natively on RDNA2 (`gfx1036`)** via `tools/hw_oracle` (Ryzen 7 9800X3D iGPU, Linux AMDGPU DRM): 672/672 exact across 21 representative IEEE-754 values (including 5 sNaNs) × 4 modifier forms (`v`, `-v`, ` `cs_cmpx_class_f32` checks both encodings with quiet NaN, positive infinity and signed zero, and verifies that a previously inactive lane stays inactive. GPU-checked on an RTX 4070 SUPER (driver 616.92). \| v \| `, `- \| v \| `) × 10 class bits for both `v_cmp_class_f32_e64` and `v_cmpx_class_f32_e64` in wave32 and wave64 across all four `(IEEE=0/1, denorm32=0/3)` modes (until 2026-11-22 `Gen.cmp_class` used `src_f` → `FAbs`/`OpFNegate`, which quieted modified sNaNs in `spirv_mini_interp.py`). 672/672 exact across 21 representative IEEE-754 values (including 5 sNaNs) × 4 modifier forms (`v`, `-v`, `\|v\|`, `-\|v\|`) × 10 class bits for both `v_cmp_class_f32_e64` and `v_cmpx_class_f32_e64` in wave32 and wave64 across all four `(IEEE=0/1, denorm32=0/3)` modes (until 2026-11-22 `Gen.cmp_class` used `src_f` → `FAbs`/`OpFNegate`, which quieted modified sNaNs in `spirv_mini_interp.py`). Corpus count (26,503 shaders): `v_cmp_class_f32` appears 37,026 times in 7,101 shaders (0 with VOP3 `abs`/`neg` on `src0`). Checked on CPU + `spirv-val` by `tests/semantic/test_cmp_class_f32_mods.py` and `tests/semantic/test_valu_f32_class_rndne.py`; `cs_cmpx_class_f32` checks both encodings with quiet NaN, positive infinity and signed zero, and verifies that a previously inactive lane stays inactive (GPU-checked on RTX 4070 SUPER driver 616.92 and AMD RX 9070 XT RADV Mesa 26.2.6, plus direct Vulkan compute verification of modified sNaNs on RX 9070 XT and Radeon 610M `gfx1036`). | | Float controls (NaN, ±inf, −0) (SHADER-99) | RDNA2 float ops return NaN, ±inf and −0 as computed, and Vulkan lets the driver assume none of them occur unless the module says otherwise. Every module therefore declares `OpExecutionMode %main SignedZeroInfNanPreserve 32` (capability `SignedZeroInfNanPreserve`, core since SPIR-V 1.4). Its index entry lists `"float_controls": ["shaderSignedZeroInfNanPreserveFloat32"]`, the device property it needs; `vk_pipeline_check` skips the shader where that property is false, and `--no-float-controls` leaves the mode out. Measured on AMD Radeon RX 9070 XT (driver 26.11.2). Without the mode, `runtime/test/shaders/cs_signed_zero_nan.asm` gets 0 in out[4..7]: the `x != x` NaN checks fold to false and a NaN `v_cvt_f16_f32` is lost. The f16 fuzzer (`tools/valu_fuzz.py --family f16`) also saw `v_pk_mul_f16` −0 products come back +0, and, with integer f16 narrowing (#575), NaN results that were never stored. With the mode, the test and those programs match. Other drivers, from testers in #664: RADV (RX 7800 XT) folds the f16 NaN check (out[6]) without the mode; NVIDIA and Intel Arc keep all three either way. Apple GPUs (MoltenVK) report the property, and the mode fixes their NaN checks, but −0 products (out[0], out[2], out[3]) still come back +0 with or without it (#1203, SHADER-182). `check.py` and `scripts/run_gpu_tests.py` don't judge those three words on an Apple device. Mesa's llvmpipe, where the CI runs these tests, returns 0 for the `0 × inf` NaN check (out[5]) with or without the mode, while its other NaN checks give 1 (#664), so out[5] isn't judged there (`UNJUDGED_WORDS` in `check.py`). f64 has its own row below (SHADER-597); its `SignedZeroInfNanPreserve 64` isn't declared yet. | | Float controls (f16 denormals) (SHADER-526) | RDNA2 keeps f16 denormals, so every module also declares `OpExecutionMode %main DenormPreserve 16` (capability `DenormPreserve`, core since SPIR-V 1.4 like `SignedZeroInfNanPreserve`, so no extension at `--target-env vulkan1.2`). The translator models f16 arithmetic in f32 with integer narrowing (`Gen.f16_bits`), so an f16 denormal is an ordinary f32 value in the module and no f32 denormal is involved: the 16-bit mode is what governs the f16→f32 conversion the driver emits for an f16 source. NVIDIA flushed that conversion without it: in `runtime/test/shaders/ps_sdwa_f16_const.asm` the y lane (`src0_sel:BYTE_1` of `2.0` is the denormal 0x0040 = 2^−18, × 1024.0 = 2^−8 = 0x1c00) read 0x0000, 4096/4096 pixels wrong, while x, z and w matched; with the mode the test is 4096/4096 exact (RTX 4070 SUPER, driver 610.88, Windows 11, validation layers on). The same lane read 0x0000 on an RTX 3090 (driver 610.88, found by @Rainmaker33). Assembling the same module with only the two `DenormPreserve` lines removed reads 0x0000 again, so it is the mode the driver honours, not a change in the translated code. Not every NVIDIA build flushes it: on `main` without the mode an RTX 4060 Ti (621.24), an RTX 5070 Ti (620.73.04, Linux) and an RTX 5080 (616.92) pass the test. The index entry lists `"shaderDenormPreserveFloat16"` after `"shaderSignedZeroInfNanPreserveFloat32"`; `vk_pipeline_check` skips the shader where the device reports that property false, and `--no-float-controls` leaves both modes out. Where the property is false the module has no f16 denormal guarantee, so an f16 denormal read can come back +0 exactly as in that lane above (NVIDIA's default without the mode); that is a value difference in the shader, and the GPU test's y lane is then expected to fail. The AMD Radeon iGPU (RDNA2, driver 24.10.24, Vulkan 1.3.280) reports `shaderDenormPreserveFloat16` true with `denormBehaviorIndependence` `32_BIT_ONLY`, and `vk_pipeline_check` builds the module and its pipeline there (`ps_sdwa_f16_const`: 1 module ok, 1 pipeline ok, wave32 and wave64); the GPU test itself skips on that device, which has 128 push-constant bytes where the test needs 144. `tests/semantic/test_f16_denorm_preserve.py` pins the mode, the index property and the four words. | diff --git a/docs/testing.md b/docs/testing.md index eda140a9a9..4d76e9f2e8 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -373,6 +373,30 @@ canonicalization at word 206, a NaN test that ignores the low dword at word 28, dword at word 70, the raw result written to an inactive lane's VCC at word 2, `v_cmpx_` replacing EXEC at word 3, `abs` ignored and `nlt` lowered as the negation of `le` at word 0. +`cs_w32_round_f64` checks `v_trunc_f64`, `v_ceil_f64`, `v_rndne_f64` and `v_floor_f64`, which the translator gives +to the driver's double-precision `Trunc`, `Ceil`, `RoundEven` and `Floor` (`shaderFloat64`). 64 inputs are loaded at +run time: signed zeros, the smallest subnormals and normals, values around 0.5 and 1 (the largest value below 0.5 +among them), ties from 0.5 to 5.5 and at 2^31 + 0.5, 2^51 + 0.5 and 2^52 - 0.5, integers from 2^52 to 2^63, 1e300, +the largest finite value, the infinities, and quiet and signalling NaNs. Each thread stores the four roundings, +`v_trunc_f64` with a `neg` source, `v_ceil_f64` with an `abs` source, a `v_floor_f64` whose destination pair overlaps +its source pair, and a `v_rndne_f64` run with the odd threads turned off, whose destination must keep the pair it +held. The expected words come from Python (`round_f64` in `check.py`: exact IEEE-754, the result keeping its +source's sign), and `tests/test_gpu_round_f64.py` checks that oracle against exact rational rounding. Two kinds of +input are judged by what Vulkan lets a driver do, not by RDNA2: a NaN may come back as another NaN, and a subnormal +may be read as a zero of its sign, because the module does not declare `DenormPreserve` for 64 bits. All 1152 heap +words are judged, the 128 unchanged input words included. Run it alone with +`python -I scripts/run_gpu_tests.py --build runtime/build --filter cs_w32_round_f64 --require-pass`. +It needs `shaderFloat64`; a device without it reports a skip. + +Measured: on an RTX 4070 Ti (NVIDIA 620.70.06, Linux) 497 of the 512 results are RDNA2's, and the other 15 are those +of the two signalling NaNs, which come back quiet with sign and payload kept (`0x7ff0000000000001` gives +`0x7ff8000000000001`). On llvmpipe (Mesa 26.2.6, LLVM 23.1.4) five more differ: the two smallest subnormals are read +as zero, so `v_ceil_f64` of the positive one gives +0 instead of 1 and `v_floor_f64` of the negative one -0 instead +of -1. Rules broken one at a time each failed the test on both devices: `rndne` lowered as `floor(x + 0.5)` (word +20, the sign of -0), `trunc` or `ceil` lowered as `Floor`, the `neg` or the `abs` source modifier ignored (words 8 and +26), the low result word taken from the high one (word 8), and the fixture without its `v_cmpx` (word 30). Replacing +`RoundEven` by GLSL `Round` changed nothing on either device: both send a tie to the even integer. + ## Wave64 pixel, vertex and geometry shaders (`w64_graphics.py`) Graphics stages have no emulation: on a 32-wide subgroup a wave64 VS, PS or GS runs as two 32-lane halves, and the diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py index b2d3013913..3c3f45928c 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py @@ -447,6 +447,122 @@ def cmp_f64_test(tools, spirv, env=None): return dump_test(tools, spirv, "cs_w32_cmp_f64", expected, len(expected), child) +# cs_w32_round_f64.asm: the binary64 input of each thread, a value and its negative side by side. +ROUND_F64_VALUES = ( + 0x0000000000000000, 0x8000000000000000, # +0, -0 + 0x0000000000000001, 0x8000000000000001, # the smallest subnormal and its negative + 0x3FD0000000000000, 0xBFD0000000000000, # +-0.25 + 0x3FDFFFFFFFFFFFFF, 0xBFDFFFFFFFFFFFFF, # +-the largest value below 0.5: x + 0.5 already rounds to 1 + 0x3FE0000000000000, 0xBFE0000000000000, # +-0.5, a tie that goes to 0 + 0x3FE0000000000001, 0xBFE0000000000001, # +-the value just above 0.5 + 0x3FE8000000000000, 0xBFE8000000000000, # +-0.75 + 0x3FEFFFFFFFFFFFFF, 0xBFEFFFFFFFFFFFFF, # +-the value just below 1 + 0x3FF0000000000000, 0xBFF0000000000000, # +-1 + 0x3FF0000000000001, 0xBFF0000000000001, # +-the value just above 1 + 0x3FF8000000000000, 0xBFF8000000000000, # +-1.5, a tie that goes to 2 + 0x4004000000000000, 0xC004000000000000, # +-2.5, a tie that goes to 2 + 0x400C000000000000, 0xC00C000000000000, # +-3.5, a tie that goes to 4 + 0x4003FFFFFFFFFFFF, 0xC004000000000001, # just below 2.5, and just beyond -2.5 + 0x4320000000000001, 0xC320000000000001, # +-(2^51 + 0.5), a tie that goes to 2^51 + 0x4320000000000003, 0xC320000000000003, # +-(2^51 + 1.5), a tie that goes to 2^51 + 2 + 0x432FFFFFFFFFFFFF, 0xC32FFFFFFFFFFFFF, # +-(2^52 - 0.5), the largest value with a fraction; a tie to 2^52 + 0x4330000000000000, 0x4330000000000001, # 2^52, and the odd integer 2^52 + 1 + 0xC330000000000001, 0x433FFFFFFFFFFFFF, # -(2^52 + 1), and 2^53 - 1 + 0x4340000000000000, 0x43E0000000000000, # 2^53, and 2^63 + 0xC3E0000000000000, 0x7E37E43C8800759C, # -2^63, and 1e300 + 0xFE37E43C8800759C, 0x7FEFFFFFFFFFFFFF, # -1e300, and the largest finite value + 0xFFEFFFFFFFFFFFFF, 0x7FF0000000000000, # its negative, and +inf + 0xFFF0000000000000, 0x7FF8000000000000, # -inf, and a quiet NaN + 0xFFF8000000000000, 0x7FF0000000000001, # a negative quiet NaN, and a signalling NaN (payload in the low dword) + 0xFFF0000080000000, 0x7FF8DEADBEEF1234, # a negative signalling NaN, and a quiet NaN with a payload + 0x419D6F3454400000, 0xC19D6F3457000000, # 123456789.0625, and -123456789.75 + 0x3FB999999999999A, 0xBFB999999999999A, # +-0.1 + 0x4012000000000000, 0xC012000000000000, # +-4.5, a tie that goes to 4 + 0x4016000000000000, 0xC016000000000000, # +-5.5, a tie that goes to 6 + 0x0010000000000000, 0x8010000000000000, # +-the smallest normal + 0x41E0000000100000, 0xC1E0000000100000) # +-(2^31 + 0.5), a tie that goes to 2^31 +ROUND_F64_SIGN = 1 << 63 +ROUND_F64_KEPT = 0xCAFEF00DDEADBEEF # the pair an inactive lane keeps: 0xdeadbeef low, 0xcafef00d high + + +def f64_is_nan(bits): + return bits & 0x7FF0000000000000 == 0x7FF0000000000000 and bits & 0x000FFFFFFFFFFFFF != 0 + + +def f64_is_subnormal(bits): + return bits & 0x7FF0000000000000 == 0 and bits & 0x000FFFFFFFFFFFFF != 0 + + +def round_f64(op, bits): + """The binary64 pattern RDNA2 gives for `bits` rounded to an integral value by "trunc", "ceil", "rndne" or + "floor" (docs/design.md): exact IEEE-754, a tie of rndne going to the even integer, the result keeping the + sign of the source even when it is zero, and an infinity or a NaN coming back unchanged.""" + x = struct.unpack("> 32)) + for x in ROUND_F64_VALUES: + inputs.extend((x & 0xFFFFFFFF, x >> 32)) + return [0xEEEEEEEE] * len(results) + inputs, results + inputs + + +def round_f64_problem(got): + """Judge a readback of cs_w32_round_f64: "" or the first word that is wrong. Every result is exact except for + the two kinds of source Vulkan leaves to the driver's double-precision rounding: a NaN may come back as any NaN + (a signalling one comes back quiet on the drivers measured), and a subnormal may be read as a zero of its sign, + because the module does not declare DenormPreserve for 64 bits.""" + _, expected = round_f64_words() + results = [result for thread in round_f64_results() for result in thread] + for index, (op, source) in enumerate(results): + value = got[2 * index] | got[2 * index + 1] << 32 + want = expected[2 * index] | expected[2 * index + 1] << 32 + if value == want: + continue + if op is not None and f64_is_nan(source) and f64_is_nan(value): + continue + if op is not None and f64_is_subnormal(source) and value == round_f64(op, source & ROUND_F64_SIGN): + continue + what = "the pair an inactive lane keeps" if op is None else f"{op} of {source:#018x}" + return f"word {2 * index} (thread {index // 8}): {what} gave {value:#018x}, expected {want:#018x}" + for index in range(2 * len(results), len(expected)): + if got[index] != expected[index]: + return f"word {index}: an input changed, expected {expected[index]:#010x}, got {got[index]:#010x}" + return "" + + +def round_f64_test(tools, spirv, env=None): + """Verify the four binary64 roundings on 64 memory-fed inputs, including the untouched input records.""" + initial, expected = round_f64_words() + with tempfile.TemporaryDirectory(prefix="leonida-round-f64-") as tmp: + path = Path(tmp) / "input.bin" + path.write_bytes(struct.pack(f"<{len(initial)}I", *initial)) + child = dict(os.environ if env is None else env, VKC_HEAP_INIT=str(path)) + child.setdefault("VKC_SUBGROUP_SIZE", str(subgroup_size(spirv, "cs_w32_round_f64") or 32)) + return dump_test(tools, spirv, "cs_w32_round_f64", expected, len(expected), child, judge=round_f64_problem) + + # cs_user_sgprs.asm: vk_compute_test puts these words in s4..s7 and the shader stores them back. USER_SGPRS = [0x4F000000, 0xDEADBEEF, 7, 0xFFFFFFFF] USER_SGPRS_ENV = {"VKC_SGPRS": ",".join(hex(w) for w in USER_SGPRS)} @@ -801,9 +917,10 @@ def failure(code, output, lines): return f"exit {code}: {details or 'no test output'}" -def dump_test(tools, spirv, name, want, words, env=None): +def dump_test(tools, spirv, name, want, words, env=None, judge=None): """Run one group with a heap of `words` words and compare the first len(want) words of the whole dump. The - console dump stops at word 7.""" + console dump stops at word 7. With `judge`, the whole dump goes to it instead, as a tuple of words, and its + answer ("" for a pass) is returned.""" with tempfile.TemporaryDirectory(prefix="leonida-fmt-") as tmp: dump = Path(tmp) / "out.bin" # VKC_OUT_WORDS sets a minimum. Pin this dispatch to exactly `words` words. @@ -819,6 +936,8 @@ def dump_test(tools, spirv, name, want, words, env=None): data = dump.read_bytes() if len(data) != 4 * words: return f"expected {4 * words} dump bytes, got {len(data)}" + if judge: + return judge(struct.unpack(f"<{words}I", data)) for i, (expected, got) in enumerate(zip(want, struct.unpack(f"<{words}I", data))): if got != expected: return f"word {i}: expected {expected:#010x}, got {got:#010x}" @@ -1944,6 +2063,7 @@ def main(): expected_words=HEAP_INIT_EXPECTED, env=heap_init_env()))) results.append(("cs_w32_shift64", shift64_test(tools, spirv))) results.append(("cs_w32_cmp_f64", cmp_f64_test(tools, spirv))) + results.append(("cs_w32_round_f64", round_f64_test(tools, spirv))) results.append(("cs_cvt_f32_sat", cvt_f32_sat_test(tools, spirv))) results.append(("cs_fma_fused", fma_fused_test(tools, spirv))) results.append(("cs_cvt_pk_u8", compute_test(tools, spirv, "cs_cvt_pk_u8", "1", "dump", diff --git a/runtime/test/shaders/cs_w32_round_f64.asm b/runtime/test/shaders/cs_w32_round_f64.asm new file mode 100644 index 0000000000..809a793d71 --- /dev/null +++ b/runtime/test/shaders/cs_w32_round_f64.asm @@ -0,0 +1,56 @@ +; GPU-ROUND-F64: round binary64 to an integral value, v_trunc_f64, v_ceil_f64, v_rndne_f64 and v_floor_f64. +; group: 64,1,1 +; mattr: +wavefrontsize32,-wavefrontsize64 +; check.py seeds 64 binary64 inputs at byte 0x1000, {lo, hi} each: signed zeros, the smallest subnormals and +; normals, values around 0.5 and 1 (the largest value below 0.5 among them), ties at 0.5, 1.5, 2.5, 3.5, 4.5 and 5.5, +; ties at 2^31 + 0.5, 2^51 + 0.5 and 2^52 - 0.5, the integers 2^52, 2^52 + 1, 2^53 - 1, 2^53 and 2^63, 1e300, the +; largest finite value, the infinities, quiet NaNs with and without a payload and two signalling NaNs. Thread i +; reads input i from memory, so neither the translator nor the driver can fold a rounding, and writes eight results +; of two words (low first) at byte 64 * i: +; +0 v_trunc_f64 x toward zero +; +8 v_ceil_f64 x toward +infinity +; +16 v_rndne_f64 x to nearest, a tie to the even integer +; +24 v_floor_f64 x toward -infinity +; +32 v_trunc_f64 -x VOP3 neg: the sign bit is flipped first +; +40 v_ceil_f64 |x| VOP3 abs: the sign bit is cleared first +; +48 v_floor_f64 x the destination pair v[21:22] overlaps the source pair v[20:21] +; +56 v_rndne_f64 x with the odd threads turned off first: they keep the pair 0xdeadbeef, +; 0xcafef00d that was in the destination +; RDNA2 ISA VOP1 opcodes 23..26. A result that is zero keeps the sign of its source (ceil of -0.25 is -0), a value +; of magnitude 2^52 or more is already integral, an infinity stays, and on the hardware a NaN and a subnormal are +; rounded like any other value: a NaN comes back unchanged, ceil of the smallest subnormal is 1 and floor of its +; negative is -1 (docs/design.md). The translator gives the four ops to the driver's double-precision Trunc, Ceil, +; RoundEven and Floor, so check.py judges two kinds of input by what Vulkan lets a driver do with them: a NaN may +; come back as another NaN (a signalling one comes back quiet on the drivers measured), and a subnormal may be read +; as a zero of its sign, since the module does not ask for binary64 denormals to be kept. Every other word is exact, +; and the input records must come back unchanged. +; Run with the heap initialized by check.py's round_f64_test; all 1152 words are judged. +v_lshlrev_b32_e32 v1, 3, v0 +v_add_nc_u32_e32 v1, 0x1000, v1 +v_lshlrev_b32_e32 v10, 6, v0 +v_and_b32_e32 v9, 1, v0 +buffer_load_dwordx2 v[2:3], v1, s[0:3], 0 offen +s_waitcnt vmcnt(0) +v_trunc_f64_e32 v[4:5], v[2:3] +v_ceil_f64_e32 v[6:7], v[2:3] +v_rndne_f64_e32 v[12:13], v[2:3] +v_floor_f64_e32 v[14:15], v[2:3] +v_trunc_f64_e64 v[16:17], -v[2:3] +v_ceil_f64_e64 v[18:19], |v[2:3]| +v_mov_b32_e32 v20, v2 +v_mov_b32_e32 v21, v3 +v_floor_f64_e32 v[21:22], v[20:21] +v_mov_b32_e32 v24, 0xdeadbeef +v_mov_b32_e32 v25, 0xcafef00d +v_cmpx_eq_u32_e32 0, v9 +v_rndne_f64_e32 v[24:25], v[2:3] +s_mov_b32 exec_lo, -1 +buffer_store_dwordx2 v[4:5], v10, s[0:3], 0 offen +buffer_store_dwordx2 v[6:7], v10, s[0:3], 0 offen offset:8 +buffer_store_dwordx2 v[12:13], v10, s[0:3], 0 offen offset:16 +buffer_store_dwordx2 v[14:15], v10, s[0:3], 0 offen offset:24 +buffer_store_dwordx2 v[16:17], v10, s[0:3], 0 offen offset:32 +buffer_store_dwordx2 v[18:19], v10, s[0:3], 0 offen offset:40 +buffer_store_dwordx2 v[21:22], v10, s[0:3], 0 offen offset:48 +buffer_store_dwordx2 v[24:25], v10, s[0:3], 0 offen offset:56 +s_endpgm diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index fa69a5f1ee..aac6efeeed 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -38,6 +38,7 @@ from check import HEAP_INIT_EXPECTED, heap_init_env # cs_heap_init: vk_compute_test's VKC_HEAP_INIT 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 from check import judged_words, words_match # dump words not judged on some devices (cs_signed_zero_nan) from check import TEXOFF_ARGS, texoff_problem # ps_texoff's expected words and arguments live in check.py from check import TEXOFF_FALLBACK, texoff_env # LEONIDA_TEXOFF_FALLBACK=1: texel offsets without maintenance8 @@ -992,6 +993,10 @@ def run_suite(a, work: str) -> int: detail = cmp_f64_test(a.build, spirv_dir, cs_env) results.append((name, None if isinstance(detail, Skip) else not detail, detail or "1536 words exact (256 operand pairs and unchanged inputs)")) + elif name == "cs_w32_round_f64": + detail = round_f64_test(a.build, spirv_dir, cs_env) + results.append((name, None if isinstance(detail, Skip) else not detail, + detail or "1152 words judged (64 inputs, eight roundings each, and unchanged inputs)")) elif name == "cs_workgroup_yz": rc, msg = run_cmd([vk_compute, spv, "2x3x4", "workgroup_yz"], env=cs_env) results.append((name,) + compute_result(rc, msg, rc == 0 and "2x3x4 workgroup Y/Z: 0 mismatches" diff --git a/tests/test_gpu_round_f64.py b/tests/test_gpu_round_f64.py new file mode 100644 index 0000000000..52b763ebf7 --- /dev/null +++ b/tests/test_gpu_round_f64.py @@ -0,0 +1,246 @@ +"""GPU-ROUND-F64: the binary64 rounding oracle, its judge, the readback and the runner verdicts, without a GPU.""" +import contextlib +from fractions import Fraction +import io +import math +from pathlib import Path +import struct +import sys +import tempfile +from types import SimpleNamespace +import unittest +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "scripts")) +import run_gpu_tests as rgt +import check + +WORDS = 1152 # 64 threads of eight two-word results, then 64 two-word inputs +RESULTS = 1024 +FIXTURE = ROOT / "runtime" / "test" / "shaders" / "cs_w32_round_f64.asm" +OPS = ("trunc", "ceil", "rndne", "floor") + + +def bits_of(value): + return struct.unpack("> 32 + return change + + def test_the_hardware_s_words_pass(self): + self.assertEqual(self.judge(lambda data: None), "") + + def test_a_nan_may_come_back_as_another_nan_but_not_as_a_number(self): + signalling = check.ROUND_F64_VALUES.index(0x7FF0000000000001) + self.assertEqual(self.judge(self.set_result(signalling, 0, 0x7FF8000000000001)), "") # quieted + self.assertEqual(self.judge(self.set_result(signalling, 4, 0x7FF8000000000000)), "") # sign and payload lost + self.assertIn("trunc of 0x7ff0000000000001 gave 0x7ff0000000000000", + self.judge(self.set_result(signalling, 0, 0x7FF0000000000000))) # an infinity + # A number does not come back as a NaN. + self.assertIn("ceil of", self.judge(self.set_result(16, 1, 0x7FF8000000000000))) + + def test_a_subnormal_may_be_read_as_a_zero_of_its_sign_and_nothing_else(self): + sign = check.ROUND_F64_SIGN + self.assertEqual(self.judge(self.set_result(2, 1, 0)), "") # ceil of +sub read as +0 + self.assertEqual(self.judge(self.set_result(3, 3, sign)), "") # floor of -sub read as -0 + self.assertIn("ceil of 0x0000000000000001", self.judge(self.set_result(2, 1, sign))) + self.assertIn("floor of 0x8000000000000001", self.judge(self.set_result(3, 3, 0))) + self.assertIn("trunc of 0x0000000000000001", self.judge(self.set_result(2, 0, bits_of(1.0)))) + + def test_everything_else_is_exact(self): + tie = check.ROUND_F64_VALUES.index(bits_of(2.5)) + for thread, slot, wrong, what in ((tie, 2, bits_of(3.0), "rndne of 0x4004000000000000"), + (1, 2, 0, "rndne of 0x8000000000000000"), # -0 came back as +0 + (5, 1, 0, "ceil of 0xbfd0000000000000"), # ceil of -0.25 is -0 + (16, 5, bits_of(2.0), "ceil of 0x3ff0000000000000"), + (9, 7, 0, "the pair an inactive lane keeps")): + with self.subTest(what=what): + result = self.judge(self.set_result(thread, slot, wrong)) + self.assertIn(f"word {word(thread, slot)} (thread {thread}): {what}", result) + self.assertIn(f"word {RESULTS}: an input changed", self.judge(lambda data: data.__setitem__(RESULTS, 1))) + self.assertIn(f"word {WORDS - 1}: an input changed", + self.judge(lambda data: data.__setitem__(WORDS - 1, 0))) + + +class RoundF64Fixture(unittest.TestCase): + def test_assembly_stores_the_eight_results_the_oracle_lists(self): + lines = [ln.strip() for ln in FIXTURE.read_text(encoding="utf-8").splitlines()] + code = [ln for ln in lines if ln and not ln.startswith(";")] + self.assertIn("; group: 64,1,1", lines) + self.assertEqual(code, [ + "v_lshlrev_b32_e32 v1, 3, v0", "v_add_nc_u32_e32 v1, 0x1000, v1", "v_lshlrev_b32_e32 v10, 6, v0", + "v_and_b32_e32 v9, 1, v0", + "buffer_load_dwordx2 v[2:3], v1, s[0:3], 0 offen", "s_waitcnt vmcnt(0)", + "v_trunc_f64_e32 v[4:5], v[2:3]", "v_ceil_f64_e32 v[6:7], v[2:3]", + "v_rndne_f64_e32 v[12:13], v[2:3]", "v_floor_f64_e32 v[14:15], v[2:3]", + "v_trunc_f64_e64 v[16:17], -v[2:3]", "v_ceil_f64_e64 v[18:19], |v[2:3]|", + "v_mov_b32_e32 v20, v2", "v_mov_b32_e32 v21, v3", "v_floor_f64_e32 v[21:22], v[20:21]", + "v_mov_b32_e32 v24, 0xdeadbeef", "v_mov_b32_e32 v25, 0xcafef00d", + "v_cmpx_eq_u32_e32 0, v9", "v_rndne_f64_e32 v[24:25], v[2:3]", "s_mov_b32 exec_lo, -1", + "buffer_store_dwordx2 v[4:5], v10, s[0:3], 0 offen", + "buffer_store_dwordx2 v[6:7], v10, s[0:3], 0 offen offset:8", + "buffer_store_dwordx2 v[12:13], v10, s[0:3], 0 offen offset:16", + "buffer_store_dwordx2 v[14:15], v10, s[0:3], 0 offen offset:24", + "buffer_store_dwordx2 v[16:17], v10, s[0:3], 0 offen offset:32", + "buffer_store_dwordx2 v[18:19], v10, s[0:3], 0 offen offset:40", + "buffer_store_dwordx2 v[21:22], v10, s[0:3], 0 offen offset:48", + "buffer_store_dwordx2 v[24:25], v10, s[0:3], 0 offen offset:56", + "s_endpgm"]) + # The order of the stores is the order of round_f64_results, and the pair an odd thread keeps is the one + # the two moves put there. + self.assertEqual([op for op, _ in check.round_f64_results()[0]], + ["trunc", "ceil", "rndne", "floor", "trunc", "ceil", "floor", "rndne"]) + self.assertEqual(check.round_f64_results()[1][7], (None, 0xCAFEF00DDEADBEEF)) + x = check.ROUND_F64_VALUES[5] + self.assertEqual(check.round_f64_results()[5][4:6], + [("trunc", x ^ check.ROUND_F64_SIGN), ("ceil", x & ~check.ROUND_F64_SIGN)]) + + +class RoundF64Readback(unittest.TestCase): + def run_readback(self, mutate=None, code=0, output="", missing=False): + paths = [] + + def launch(*args, env): + paths.append(Path(env["VKC_HEAP_INIT"])) + initial, expected = check.round_f64_words() + self.assertEqual(args[1:], (str(Path("unused") / "cs_w32_round_f64.spv"), "1", "dump")) + self.assertEqual(paths[-1].read_bytes(), struct.pack(f"<{WORDS}I", *initial)) + self.assertEqual(env["VKC_SUBGROUP_SIZE"], "32") + self.assertEqual(env["VKC_OUT_WORDS"], str(WORDS)) + self.assertEqual(env["LEONIDA_VK_DEVICE"], "synthetic device") + if mutate: + mutate(expected) + if not missing: + Path(env["VKC_DUMP"]).write_bytes(struct.pack(f"<{len(expected)}I", *expected)) + return code, output + + with patch.object(check, "run", side_effect=launch): + result = check.round_f64_test("unused", "unused", {"LEONIDA_VK_DEVICE": "synthetic device"}) + self.assertEqual(len(paths), 1) + self.assertFalse(paths[0].exists(), "private heap input must be cleaned up") + return result + + def test_complete_readback_passes(self): + self.assertEqual(self.run_readback(), "") + + def test_a_wrong_result_or_a_changed_input_fails(self): + for index in (0, RESULTS - 1, RESULTS, WORDS - 1): + with self.subTest(word=index): + result = self.run_readback(lambda data: data.__setitem__(index, data[index] ^ 0x00100000)) + self.assertIn(f"word {index - index % 2 if index < RESULTS else index}", result) + + def test_truncated_and_missing_dump_fail(self): + self.assertIn(f"expected {4 * WORDS} dump bytes, got {4 * WORDS - 4}", + self.run_readback(lambda data: data.pop())) + self.assertIn("no VKC_DUMP", self.run_readback(missing=True)) + + def test_unsupported_float64_skips_but_nonzero_exit_fails(self): + self.assertIsInstance(self.run_readback(code=77, output="unsupported: no Float64\n"), check.Skip) + self.assertIn("exit 1", self.run_readback(code=1, output="dispatch failed")) + + +class RoundF64Runner(unittest.TestCase): + def test_filtered_runner_counts_pass_failure_and_skip(self): + for detail, expected, verdict in (("", 0, "1/1 passed"), ("word 132: mismatch", 1, "0/1 passed"), + (check.Skip("SKIP (no Float64)"), 0, "0/1 passed, 1 skipped")): + with self.subTest(detail=detail), tempfile.TemporaryDirectory() as tmp: + args = SimpleNamespace(filter="cs_w32_round_f64", build=tmp, llvm_mc="unused") + + def translate(_cmd, **_kwargs): + (Path(tmp) / "spirv" / "cs_w32_round_f64.spv").touch() + return 0, "" + + output = io.StringIO() + with (patch.object(rgt, "assemble_to_s", side_effect=lambda _mc, _src, dst, _name: Path(dst).touch()), + patch.object(rgt, "spirv_as"), patch.object(rgt, "run_cmd", side_effect=translate), + patch.object(rgt, "round_f64_test", return_value=detail) as readback, + contextlib.redirect_stdout(output)): + self.assertEqual(rgt.run_suite(args, tmp), expected) + readback.assert_called_once() + self.assertIn(verdict, output.getvalue()) + self.assertIn("cs_w32_round_f64", output.getvalue()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_shader_checks.py b/tests/test_shader_checks.py index 2e1bdee4c8..5557362a9f 100644 --- a/tests/test_shader_checks.py +++ b/tests/test_shader_checks.py @@ -36,9 +36,9 @@ + 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) + 18) # three mesh fixtures, ps_tex, ps_imgatomic, ps_table_fetch, six compute fixtures, + + len(check.TEXTURE_CONSTANTS) + 19) # three mesh fixtures, ps_tex, ps_imgatomic, ps_table_fetch, six compute fixtures, # ps_ssharp, vs_base_ids, main's standalone cs_fmt_d16_xyz / cs_heap_init dumps (net one more case), cs_fmt_all, - # cs_w32_shift64 and cs_w32_cmp_f64 + # cs_w32_shift64, cs_w32_cmp_f64 and cs_w32_round_f64 CVT = {bits: [u, s] for bits, u, s in check.CVT_F32_SAT_CASES} @@ -113,6 +113,14 @@ def harness(_tool, shader, *args, env=None): words = expected if seeded else initial Path(env["VKC_DUMP"]).write_bytes(struct.pack(f"<{len(words)}I", *words)) return 0, "" + if name == "cs_w32_round_f64": + # The rounded words come back only if check.py seeded the inputs through VKC_HEAP_INIT. + initial, expected = check.round_f64_words() + self.assertEqual((args, env["VKC_OUT_WORDS"]), (("1", "dump"), str(len(expected)))) + seeded = Path(env["VKC_HEAP_INIT"]).read_bytes() == struct.pack(f"<{len(initial)}I", *initial) + words = expected if seeded else initial + Path(env["VKC_DUMP"]).write_bytes(struct.pack(f"<{len(words)}I", *words)) + return 0, "" if name == "cs_user_sgprs": # The seeded words come back only if check.py passed them in VKC_SGPRS. seeded = (env or {}).get("VKC_SGPRS") == check.USER_SGPRS_ENV["VKC_SGPRS"] From 5f063e5812f9b12f5c2063c1b552fd975ae9e5e9 Mon Sep 17 00:00:00 2001 From: milk4sale <53350507+milk4sale@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:32:48 -0600 Subject: [PATCH 2/3] tests, rdna2spirv: GPU readback for frexp and ldexp, and their neg/abs sources move the sign bit (GPU-FREXP-LDEXP, SHADER-FREXP-LDEXP-SIGN-MODS) v_frexp_mant_f32, v_frexp_exp_i32_f32, v_ldexp_f32, v_frexp_mant_f64 and v_frexp_exp_i32_f64 are lowered with integer ops on the float's words, and no fixture in runtime/test/shaders ran any of them. cs_w32_frexp_ldexp is memory-fed, like cs_w32_shift64: check.py seeds 64 records of a binary32 value, an ldexp exponent and a binary64 value, and each thread loads one at run time and stores the five results, v_frexp_mant_f32 with a neg source, and v_ldexp_f32 with an abs source run with the odd threads turned off. The records cover the exponent clamp, overflow and underflow, binary32 denormals, binary64 subnormals on both sides of the dword boundary, zeros, infinities and NaNs. The expected words come from an oracle written from the rows of docs/design.md, checked against math.frexp and math.ldexp in tests/test_gpu_frexp_ldexp.py. On an RTX 4070 Ti (NVIDIA 620.70.06) six words were wrong: every NaN source under neg or abs came back as 0x7fffffff, the driver's default NaN. The binary32 branch applied the modifiers as FAbs and OpFNegate, from which Vulkan lets a driver return any NaN. The three ops only move bits, so the branch now reads its source through Gen.src_u_sign_mods, as the min/max family does. tests/semantic/test_alu_frexp_ldexp.py checks that the modifiers are emitted as sign-bit ops. With that the fixture's 768 words are exact on the RTX 4070 Ti and on llvmpipe. Co-Authored-By: Claude Fable 5.2 --- docs/design.md | 4 +- docs/testing.md | 21 ++ runtime/test/shaders/check.py | 111 +++++++++ runtime/test/shaders/cs_w32_frexp_ldexp.asm | 44 ++++ scripts/run_gpu_tests.py | 5 + tests/semantic/test_alu_frexp_ldexp.py | 60 +++++ tests/test_gpu_frexp_ldexp.py | 236 ++++++++++++++++++++ tests/test_shader_checks.py | 12 +- tools/rdna2spirv.py | 4 +- 9 files changed, 492 insertions(+), 5 deletions(-) create mode 100644 runtime/test/shaders/cs_w32_frexp_ldexp.asm create mode 100644 tests/test_gpu_frexp_ldexp.py diff --git a/docs/design.md b/docs/design.md index d21ee71154..644aec6502 100644 --- a/docs/design.md +++ b/docs/design.md @@ -468,10 +468,10 @@ How the generated SPIR-V expects the runtime to work: | Float-to-int saturation | `v_cvt_u32_f32` and `v_cvt_i32_f32` truncate toward zero, saturate out-of-range values (including infinities) to the destination bounds, and return zero for NaN. The conversion operand is kept in range before emitting SPIR-V `OpConvertFToU`/`OpConvertFToS`. 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), §12.8, VOP1 opcodes 7 and 8. The synthetic `cs_cvt_f32_sat.asm` fixture is checked bit-for-bit by `tests/semantic/test_float_to_int.py`. | | `v_cvt_f16_u16`, `v_cvt_f16_i16`, `v_cvt_u16_f16`, `v_cvt_i16_f16` | Conversions of the low 16-bit half (`op_sel:[src,dst]` picks the high half of the source / of the destination in the VOP3 form where supported; GFX10 does not accept `op_sel` on these opcodes); the other half of the destination is kept, like the other 16-bit-result ops (see *16-bit results*). `v_cvt_f16_u16` / `v_cvt_f16_i16` convert the unsigned / sign-extended half and narrow with the usual f16 rounding (65520 and above give +infinity for the unsigned form). `v_cvt_u16_f16` / `v_cvt_i16_f16` truncate toward zero, saturate to [0, 65535] / [-32768, 32767] (an f16 infinity too) and give 0 for NaN, as the 32-bit conversions do (*Float-to-int saturation*). `clamp` and the output multipliers are rejected as `Unsupported` rather than guessed. Source: the 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) pseudocode. Checked on the CPU by `tests/semantic/test_alu_cvt_16.py`; **hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137): all four `_e64` forms keep the high half of the destination, `v_cvt_u16/i16_f16` give 0 for ±qNaN and saturate ±inf, and `v_cvt_f16_u16(65520)` gives +inf (`0x7c00`). Not run on the shader corpus. | | `v_cvt_norm_i16_f16`, `v_cvt_norm_u16_f16` | Normalized f16-to-16-bit integer conversions: `round_even(clamp(S0, -1, 1) * 32767)` (`i16`, snorm16) and `round_even(clamp(S0, 0, 1) * 65535)` (`u16`, unorm16), with NaN giving `0`, source `neg`/`abs` and SDWA `WORD_1` supported, and the unwritten half of the destination preserved (matching `v_cvt_i16_f16`/`v_cvt_u16_f16`; GFX10/LLVM does not accept VOP3 `op_sel` on these opcodes). For `\|cl\| >= 0.25`, `cl * (scale + 1)` is an exact even integer in f32, so `cl * (scale + 1) - RoundEven(cl)` rounds the exact product once without binary32 double-rounding ties near `±0.5`. `clamp` and output multipliers (`mul:*`/`div:*`) are rejected as `Unsupported`. VOP3 `clamp`, `mul:2`, `mul:4`, `div:2` (and combinations) and SDWA `clamp` are hardware no-ops on these integer-destination conversions and are accepted without changing output semantics; unsupported modifiers or invalid form/modifier pairs (e.g., `mul:8`, `_sdwa mul:*`, `_e32`/`_dpp` output modifiers) still 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) (`V_CVT_NORM_I16_F16`, `V_CVT_NORM_U16_F16`). **Hardware-verified on RDNA2** (AMD Radeon RDNA2 iGPU `gfx1036`, Windows 11, driver `32.0.21043.5001`, wave32 and wave64 via `tools/hw_oracle`, @Pierre-Kookis): 655,360 / 655,360 exact words across all 65,536 f16 inputs in five forms (`_e32`, `_e32 ieee=1`, `_e64 -v1`, `_e64 \|v1\|`, `_sdwa WORD_1`), including NaN → 0, ±inf clamps, denormals, single-rounding ties near ±0.5, and the untouched destination half; Checked on the CPU and with `spirv-val` by `tests/semantic/test_alu_cvt_norm_f16.py`. **Hardware-verified on RDNA2** (AMD Radeon gfx1036, wave32 and wave64, `tools/int_hw_probe.py --oracle both --group valu_cvt_norm_f16`): the same 34 inputs through both ops with the unwritten half kept and with `neg`/`abs`, bit-identical to the translator; the RDNA2 assembler takes no `op_sel` on these two opcodes, so only the VOP3P-style `pknorm` forms have an `op_sel` check. Not run on the shader corpus. **output modifiers additionally verified natively on RDNA2** (`gfx1036`, Windows 11, driver `32.0.21045.29003`, wave32 and wave64 via `tools/cvt_norm_mods_probe.py --hw-arch gfx1036`): exhaustive 65,536/65,536 f16 sweeps across VOP3 `plain`, `clamp`, `mul:2`, `mul:4`, `div:2`, `clamp mul:2`, `clamp div:2`, plus `MODE.FP_ROUND=RTZ` (`0xCC`), `IEEE=1` (`0x2C0`), `_e64` high-half preservation, and `_sdwa clamp` (`WORD_0`/`WORD_1`, `UNUSED_PRESERVE`/`UNUSED_SEXT`/`UNUSED_PAD`) all match with 0 mismatches and 0 wave diffs (`1,050,708` total word evaluations across the four probe ops). **GPU-verified through Vulkan** (wave32 synthetic compute shader via `vk_compute_test` with `VK_LAYER_KHRONOS_validation` `1.4.363`, 20 `v_cvt_norm_*` output words): bit-exact on `AMD Radeon RX 9070 XT` (driver `26.11.2 (LLPC)`, `driverVersion 2.0.416`, Vulkan `1.4.359`) and `AMD Radeon(TM) Graphics` (`gfx1036`, driver `26.11.2`, `driverVersion 2.0.353`, Vulkan `1.4.315`), 0 validation errors. Checked on the CPU and with `spirv-val` by `tests/semantic/test_alu_cvt_norm_f16.py` and `tests/semantic/test_cvt_norm_mods.py`; not run on the shader corpus. | -| `v_frexp_mant_f32`, `v_frexp_exp_i32_f32`, `v_ldexp_f32` | Computed on the binary32 word, with no float arithmetic. A normal input has a biased exponent of 1..254. `v_frexp_mant_f32` returns the input with its exponent set to 126 (a mantissa in [0.5, 1), sign kept); `v_frexp_exp_i32_f32` returns the biased exponent minus 126, so mantissa × 2^exponent is the input. Zero and denormals (read as zero) give a signed zero and exponent 0; infinities and NaNs give the input unchanged and exponent 0. `v_ldexp_f32` is S0 × 2^S1 with S1 a signed integer: S1 is clamped to [-512, 512] and added to the exponent field; a new field above 254 gives ±infinity, one of 0 or below gives ±0 (no denormal results), and zero, infinities and NaNs ignore S1. Neg/abs, `clamp` and the output multipliers apply as for other float ops (not to the integer exponent result). Source: the 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) pseudocode for these three opcodes. **Measured natively** on an RDNA2 iGPU (gfx1036, `tools/hw_oracle`): under the MODE inferred for the game (IEEE 0, f32 denormals flushed) the hardware gives the translator's word for all 30 special inputs of each frexp op and 741 ldexp cases (denormal inputs, results in and below the denormal range, every exponent clamp edge, NaN payloads). With f32 denormals kept the hardware normalizes denormal inputs and returns denormal ldexp results, and with IEEE 1 it quiets signalling NaNs; neither is modelled, since the game runs with both off. Checked on the CPU by `tests/semantic/test_alu_frexp_ldexp.py`; not run on the shader corpus. | +| `v_frexp_mant_f32`, `v_frexp_exp_i32_f32`, `v_ldexp_f32` | Computed on the binary32 word, with no float arithmetic. A normal input has a biased exponent of 1..254. `v_frexp_mant_f32` returns the input with its exponent set to 126 (a mantissa in [0.5, 1), sign kept); `v_frexp_exp_i32_f32` returns the biased exponent minus 126, so mantissa × 2^exponent is the input. Zero and denormals (read as zero) give a signed zero and exponent 0; infinities and NaNs give the input unchanged and exponent 0. `v_ldexp_f32` is S0 × 2^S1 with S1 a signed integer: S1 is clamped to [-512, 512] and added to the exponent field; a new field above 254 gives ±infinity, one of 0 or below gives ±0 (no denormal results), and zero, infinities and NaNs ignore S1. Neg/abs, `clamp` and the output multipliers apply as for other float ops (not to the integer exponent result). Source: the 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) pseudocode for these three opcodes. **Measured natively** on an RDNA2 iGPU (gfx1036, `tools/hw_oracle`): under the MODE inferred for the game (IEEE 0, f32 denormals flushed) the hardware gives the translator's word for all 30 special inputs of each frexp op and 741 ldexp cases (denormal inputs, results in and below the denormal range, every exponent clamp edge, NaN payloads). With f32 denormals kept the hardware normalizes denormal inputs and returns denormal ldexp results, and with IEEE 1 it quiets signalling NaNs; neither is modelled, since the game runs with both off. Checked on the CPU by `tests/semantic/test_alu_frexp_ldexp.py`; not run on the shader corpus. `abs` and `neg` on the float source move its sign bit on the raw word (`Gen.src_u_sign_mods`), as the three ops only move bits: through `FAbs`/`OpFNegate` every NaN source came back as the driver's default NaN, `0x7fffffff`, on an RTX 4070 Ti (NVIDIA 620.70.06), which Vulkan allows. GPU-checked by `runtime/test/shaders/cs_w32_frexp_ldexp.asm` (64 memory-fed records: the exponent clamp, overflow and underflow, denormals, zeros, infinities and NaNs, a `neg` and an `abs` source, an inactive lane): all words exact on the RTX 4070 Ti and on llvmpipe (LLVM 23.1.4). | | `v_mad_u16`, `v_mad_i16` | `D = S0 * S1 + S2` on the low 16-bit halves (VOP3 only). The product and sum are formed in 32 bits, so nothing overflows, and the low 16 bits are the result. `op_sel` bits 0..2 read the high half of a source and bit 3 writes the high half of the destination; like the other opsel-capable 16-bit VOP3 ops the other half of the destination is kept (see *16-bit results*). `clamp` saturates the full-width result to [0, 65535] (`v_mad_u16`) or [-32768, 32767] (`v_mad_i16`). Source: the 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) pseudocode and Mesa ACO's `can_use_opsel`. Checked on the CPU by `tests/semantic/test_alu_mad_u16_i16.py`; **hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137): full-width `clamp`, `op_sel` and the untouched destination half match bit-for-bit. Not run on the shader corpus. | | `v_frexp_mant_f16`, `v_frexp_exp_i16_f16`, `v_ldexp_f16` | The binary16 versions of `v_frexp_mant_f32`, `v_frexp_exp_i32_f32` and `v_ldexp_f32`, computed on the f16 word of the low half with no float arithmetic (`op_sel` picks the high half of a source; the last `op_sel` bit sends the result to the high half of the destination; the other half of the destination is kept). A normal input has a biased exponent of 1..30. `v_frexp_mant_f16` returns the input with its exponent set to 14 (a mantissa in [0.5, 1), sign kept); `v_frexp_exp_i16_f16` returns the biased exponent minus 14 as a 16-bit integer, so mantissa × 2^exponent is the input. Zero and denormals (read as zero) give a signed zero and exponent 0; infinities and NaNs give the input unchanged and exponent 0. Zero gives a signed zero and exponent 0; infinities and NaNs give the input unchanged and exponent 0. f16 denormals are kept, as in the MODE inferred for the game (`denorm_mode_16_64` = 3): a denormal input is normalized (`v_frexp_mant_f16(0x0001)` = 0.5 with exponent -23, `0x03ff` gives `0x3bfe` and -14). `v_ldexp_f16` is S0 × 2^S1 with S1 the low 16 bits of the source read as a signed integer: S1 is clamped to [-64, 64] and added to the exponent field; a new field above 30 gives ±infinity, one of 0 or below gives ±0 (no denormal results), and zero, infinities and NaNs ignore S1. S1 is clamped to [-64, 64]; a result above the f16 range gives ±infinity, and one below the smallest normal is a denormal rounded to nearest even (1.0 × 2^-15 = `0x0200`, 1.5 × 2^-24 = `0x0002`, 1.0 × 2^-25 = 0, 65504 × 2^-30 rounds up to `0x0400`); zero, infinities and NaNs ignore S1. Source neg/abs apply to the float operand. Under the game's console MODE (`0x1c0`: `IEEE=0`, `DX10_CLAMP=1`, `denorm_mode_16_64=3`) and under `IEEE=1` (`0x3c0`), VOP3 `mul:2`, `mul:4`, and `div:2` are hardware no-ops on `v_frexp_mant_f16` and `v_ldexp_f16` (since `denorm_mode_16_64=3` disables `omod` on f16 results), while `clamp` clamps to [0.0, 1.0] (negative values and NaNs clamp to +0.0, values > 1.0 and +Inf clamp to 1.0, [0.0, 1.0] kept) both alone and combined with `mul:*`/`div:*`; on `v_frexp_exp_i16_f16` (16-bit integer result), `clamp` and `mul:2`/`mul:4`/`div:2` are all hardware no-ops under every MODE (`0x1c0`, `0x100`, `0x3c0`). Under the `denorm_mode_16_64=0, IEEE=0` (`0x100`) control, `mul:2`/`mul:4`/`div:2` scale `v_frexp_mant_f16` and `v_ldexp_f16` (not modelled because the game runs with `denorm_mode_16_64=3`). Unknown or unmodelled modifiers raise `Unsupported`. Source: the 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) pseudocode for these three opcodes. **Not measured on hardware**: the denormal input and result handling, the NaN payload, and whether `v_frexp_exp_i16_f16` keeps the high half of its destination (it is modelled like the other 16-bit ops here, which keep it) are the translator's choice. **Measured natively** on an RDNA2 iGPU (gfx1036, AMD Windows driver 32.0.21045.16010, `tools/hw_oracle`) under IEEE 0, DX10_CLAMP 1, f32 denormals flushed and f16 denormals kept: the translated rule gives the hardware's word for every one of the 65,536 f16 inputs of both frexp ops and of `v_ldexp_f16` under 16 exponents (1,048,576 cases), and the high half of the destination is kept by all three. Until 2026-11-22 the translator read f16 denormals as zero and flushed denormal ldexp results, which the hardware does only with `denorm_mode_16_64` = 0. Not modelled (the game runs with IEEE 0): with IEEE 1 a signalling NaN is quieted (`0x7c01` gives `0x7e01`). VOP3 output modifiers (`clamp`, `mul:2`, `mul:4`, `div:2`, `clamp` + `mul:*`/`div:*`, and source `abs`/`neg`) were additionally measured natively on an RDNA2 iGPU (`AMD Radeon(TM) Graphics`, `gfx1036`, Windows driver `32.0.21045.29003`, wave32 & wave64 via `tools/frexp_ldexp_f16_mods_probe.py`): 3,466 / 3,466 exact words (3,360 console-MODE grid words, 22 source-modifier words, and 84 `0x100`/`0x3c0` control words, 0 wave diffs, 0 omod diffs). Checked on the CPU and with `spirv-val` by `tests/semantic/test_alu_frexp_ldexp_f16.py`, `tests/semantic/test_frexp_ldexp_f16_mods.py`, and `tests/test_frexp_ldexp_f16_mods_probe.py`; not run on the shader corpus. | -| `v_frexp_mant_f64`, `v_frexp_exp_i32_f64` | Binary64 versions of `v_frexp_mant_f32` and `v_frexp_exp_i32_f32`, computed bit-exactly on the `(lo, hi)` dword pair without requiring `OpCapability Float64` or `Int64` unless VOP3 output modifiers are used. A normal input has biased exponent `1..2046` (bits `[62:52]`): `v_frexp_mant_f64` sets the biased exponent to `1022` (`0x3FE00000`, mantissa in `[0.5, 1)` with sign and low mantissa bits kept), and `v_frexp_exp_i32_f64` returns `e - 1022` as a 32-bit signed integer so `mantissa × 2^exponent == input`. Under the default f16/f64 denormal mode (`denorm_mode_16_64` = 3, matching `v_frexp_mant_f16`/`v_frexp_exp_i16_f16`), non-zero subnormals (`e == 0`, 52-bit fraction `≠ 0`) are normalized into `[0.5, 1)` with sign preserved and exponent `msb − 1073` (`-1073..-1022`; e.g. `0x0000000000000001` → `0x3FE0000000000000` / `-1073`, `0x000FFFFFFFFFFFFF` → `0x3FEFFFFFFFFFFFFE` / `-1022`). Zero and denormals give signed zero and exponent `0`; infinities and NaNs pass through unchanged with exponent `0`. VOP3 source `abs`/`neg` flip/clear bit 31 of `hi`; VOP3 output modifiers are gated by the `MODE`, measured for this row by @fiestorra on a gfx1036 iGPU (Radeon(TM) Graphics, drivers `31.0.24002.92` and `32.0.21045.29003` (the same counts on both), raw ISA through `tools/hw_oracle`, `tools/f64_omod_probe.py`, 7 mantissa inputs x 5 modifier forms x 5 MODEs, wave32 and wave64 identical): `clamp` applies to `v_frexp_mant_f64` in every MODE via `clamp_mods_f64` (`OpCapability Float64`), while `mul:2`/`mul:4`/`div:2` scale the mantissa only under `IEEE=0` with `denorm_mode_16_64=0` and are ignored under `IEEE=1` and under `denorm_mode_16_64=3`, the mode this row assumes, so only `clamp` needs `Float64` here. All output modifiers are rejected on `v_frexp_exp_i32_f64`. 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) (`V_FREXP_MANT_F64`, `V_FREXP_EXP_I32_F64`) and LLVM `VOP1Instructions.td`. **Measured natively** on an AMD Radeon(TM) Graphics RDNA2 GPU (`gfx1036`, not the console's `gfx1013`; Windows driver 32.0.21042.62, `tools/hw_oracle`, wave32 and wave64 identical on every case): under `IEEE=0, denorm_mode_16_64=3, DX10_CLAMP=1` all 71 cases (all 52 single-bit subnormal positions `0..51`, lo/hi boundary-crossing multi-bit subnormals, negative subnormals, `±0`, normals, `±inf`, `qNaN`, `sNaN`, plus VOP3 `abs`/`neg`/`clamp`) matched bit-for-bit. Until 2026-11-22 the translator flushed binary64 subnormals to `±0` / exponent `0`, which the hardware does only under `denorm_mode_16_64=0`. Not modelled (the game runs with `IEEE=0, denorm_mode_16_64=3`): `IEEE=1` quieting signalling NaNs (`0x7FF0000000000001` → `0x7FF8000000000001`), `denorm_mode_16_64=0` flushing subnormals, and `denorm_mode_16_64=3` ignoring `omod`. **Not measured on hardware** beyond that gate: it was measured by @fiestorra with `tools/f64_omod_probe.py` (see the modifiers sentence above), while the pass-through of NaN payloads under `IEEE=0` is part of the 71 cases above and denormal-input handling follows the f32 rule. Checked on the CPU and with `spirv-val` by `tests/semantic/test_alu_frexp_f64.py`; not run on the shader corpus. | +| `v_frexp_mant_f64`, `v_frexp_exp_i32_f64` | Binary64 versions of `v_frexp_mant_f32` and `v_frexp_exp_i32_f32`, computed bit-exactly on the `(lo, hi)` dword pair without requiring `OpCapability Float64` or `Int64` unless VOP3 output modifiers are used. A normal input has biased exponent `1..2046` (bits `[62:52]`): `v_frexp_mant_f64` sets the biased exponent to `1022` (`0x3FE00000`, mantissa in `[0.5, 1)` with sign and low mantissa bits kept), and `v_frexp_exp_i32_f64` returns `e - 1022` as a 32-bit signed integer so `mantissa × 2^exponent == input`. Under the default f16/f64 denormal mode (`denorm_mode_16_64` = 3, matching `v_frexp_mant_f16`/`v_frexp_exp_i16_f16`), non-zero subnormals (`e == 0`, 52-bit fraction `≠ 0`) are normalized into `[0.5, 1)` with sign preserved and exponent `msb − 1073` (`-1073..-1022`; e.g. `0x0000000000000001` → `0x3FE0000000000000` / `-1073`, `0x000FFFFFFFFFFFFF` → `0x3FEFFFFFFFFFFFFE` / `-1022`). Zero and denormals give signed zero and exponent `0`; infinities and NaNs pass through unchanged with exponent `0`. VOP3 source `abs`/`neg` flip/clear bit 31 of `hi`; VOP3 output modifiers are gated by the `MODE`, measured for this row by @fiestorra on a gfx1036 iGPU (Radeon(TM) Graphics, drivers `31.0.24002.92` and `32.0.21045.29003` (the same counts on both), raw ISA through `tools/hw_oracle`, `tools/f64_omod_probe.py`, 7 mantissa inputs x 5 modifier forms x 5 MODEs, wave32 and wave64 identical): `clamp` applies to `v_frexp_mant_f64` in every MODE via `clamp_mods_f64` (`OpCapability Float64`), while `mul:2`/`mul:4`/`div:2` scale the mantissa only under `IEEE=0` with `denorm_mode_16_64=0` and are ignored under `IEEE=1` and under `denorm_mode_16_64=3`, the mode this row assumes, so only `clamp` needs `Float64` here. All output modifiers are rejected on `v_frexp_exp_i32_f64`. 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) (`V_FREXP_MANT_F64`, `V_FREXP_EXP_I32_F64`) and LLVM `VOP1Instructions.td`. **Measured natively** on an AMD Radeon(TM) Graphics RDNA2 GPU (`gfx1036`, not the console's `gfx1013`; Windows driver 32.0.21042.62, `tools/hw_oracle`, wave32 and wave64 identical on every case): under `IEEE=0, denorm_mode_16_64=3, DX10_CLAMP=1` all 71 cases (all 52 single-bit subnormal positions `0..51`, lo/hi boundary-crossing multi-bit subnormals, negative subnormals, `±0`, normals, `±inf`, `qNaN`, `sNaN`, plus VOP3 `abs`/`neg`/`clamp`) matched bit-for-bit. Until 2026-11-22 the translator flushed binary64 subnormals to `±0` / exponent `0`, which the hardware does only under `denorm_mode_16_64=0`. Not modelled (the game runs with `IEEE=0, denorm_mode_16_64=3`): `IEEE=1` quieting signalling NaNs (`0x7FF0000000000001` → `0x7FF8000000000001`), `denorm_mode_16_64=0` flushing subnormals, and `denorm_mode_16_64=3` ignoring `omod`. **Not measured on hardware** beyond that gate: it was measured by @fiestorra with `tools/f64_omod_probe.py` (see the modifiers sentence above), while the pass-through of NaN payloads under `IEEE=0` is part of the 71 cases above and denormal-input handling follows the f32 rule. Checked on the CPU and with `spirv-val` by `tests/semantic/test_alu_frexp_f64.py`; not run on the shader corpus. GPU-checked by `runtime/test/shaders/cs_w32_frexp_ldexp.asm` (64 memory-fed patterns: normals, 24 subnormals with single fraction bits on both sides of the dword boundary and with several bits, zeros, infinities and NaNs): both words of the mantissa and the exponent exact on an RTX 4070 Ti (NVIDIA 620.70.06, Linux) and on llvmpipe (LLVM 23.1.4). | | `v_ldexp_f64` | Binary64 load-exponent (`D.f64 = S0.f64 × 2^(S1.i32)`), lowered bit-exactly on the `(lo, hi)` dword pair using only 32-bit integer ops (no `OpCapability Float64` or `OpCapability Int64`, even with `clamp`). `±0`, `±inf`, and both quiet and signalling NaNs (under `IEEE = 0`) pass through bit-for-bit unchanged after `S0` `abs`/`neg`. Subnormal inputs (`denorm_mode_16_64 = 3`) are normalized via `FindUMsb` before adding `clamp(S1, -4096, 4096)` to the exponent field; overflow (`e2 >= 2047`) gives `±inf`, and subnormal outputs (`e2 <= 0`) shift the 53-bit significand right by `sh = 1 - e2` (`1..53`) and round to nearest even (carry into bit 52 yields `±min_norm`; `sh >= 54` flushes to `±0`). VOP3 `clamp` applies bit-exactly in integer ops (`DX10_CLAMP = 1`: `NaN`, `-0.0`, `<0` → `+0.0`; `>1.0` including `+inf` → `1.0`). VOP3 `omod` (`mul:2`/`mul:4`/`div:2`) is rejected as `Unsupported` because hardware ignores it under `denorm_mode_16_64 = 3` and applies it under `denorm_mode_16_64 = 0`. For immediate `S0` operands, inline integers `-16..64` sign-extend across 64 bits while 32-bit literals occupy `[63:32]` with `[31:0] = 0`. 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) (`V_LDEXP_F64`). **Measured natively** on an RDNA2 iGPU (`gfx1036`, Windows driver `32.0.21042.62`, wave32 and wave64 via `tools/hw_oracle` under game MODE `IEEE=0`, `DX10_CLAMP=1`, `denorm32=0`, `denorm16_64=3`): 870 / 870 cases bit-exact across all 52 subnormal input bit positions, all 54 subnormal right-shift boundaries and exact half-ULP ties, carry into `min_norm`, `±0`/`±inf`/qNaN/sNaN, `abs`/`neg`/`clamp`, immediate/literal `S0`, and seeded random inputs (not modelled: `IEEE=1` quiets signalling NaNs). Checked on the CPU and assembled by `tests/semantic/test_alu_ldexp_f64.py`; not run on the shader corpus. | | `v_min3_f16`, `v_max3_f16`, `v_min3_i16`, `v_min3_u16`, `v_max3_i16`, `v_max3_u16`, `v_med3_i16`, `v_med3_u16` | Three-operand 16-bit min/max/median (VOP3 only). `op_sel` bits 0..2 read the high half of S0..S2, bit 3 writes the high half of D, and the unwritten half of D is kept (see *16-bit results*). `v_min3_f16` and `v_max3_f16` read each selected f16 half through `Gen.f16_in` (`neg`/`abs` apply to the selected half), fold with `NMin`/`NMax` (so a NaN operand yields the other operand and −0 orders below +0, matching `v_min3_f32`/`v_max3_f32` and `v_med3_f16`), then apply VOP3 `omod`/`clamp` and `Gen.f16_out`. The 16-bit integer ops zero-extend (`u16`) or sign-extend (`i16`) the selected 16-bit halves, evaluate `UMin`/`UMax`/`UClamp` or `SMin`/`SMax`/`SClamp`, and write the low 16 bits into the selected half of D; `clamp` is supported on integer min3/max3/med3 as an identity no-op on the 16-bit container (hardware-verified on gfx1036 across wave32 and wave64); non-VGPR `op_sel` destinations raise `Unsupported`. `clamp` and non-VGPR `op_sel` destinations raise `Unsupported`. Until 2026-11-22 all eight raised `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) VOP3 opcodes `0x351`–`0x356`, `0x359`–`0x35A`, and Mesa ACO's `can_use_opsel`. **Hardware-verified on RDNA2** (gfx1036 iGPU, AMD Windows driver 32.0.21045.16010, `tools/hw_oracle`, IEEE 0 with f16 denormals kept): 6,092 cases (every triple of ±0, a denormal, 1.0, -1.0, 2.0, ±inf, a quiet and a signalling NaN for each f16 op; every triple of 8 edge values for the i16/u16 ops; `op_sel` on each source and the destination; a 0xabcd high half on every source) match the translator's word, including keeping the destination half and returning `src0`'s NaN bits unchanged (`0x7c01` stays signalling under IEEE 0) when all three operands are NaN (`ALL_NAN_SRC0_SIGNALLING` in `tests/semantic/test_alu_min3_max3_med3_16_hw.py`, alongside 540 sampled measured words). `tests/semantic/test_alu_min3_max3_med3_16_hw.py` holds 540 of the measured words. **Not GPU-verified.** CPU-checked by `tests/semantic/test_alu_min3_max3_med3_16.py`, `tests/test_f16_op_sel.py`, and `tests/test_f16_op_sel_values.py`. CPU-checked by `tests/semantic/test_alu_min3_max3_med3_16.py`, `tests/test_f16_op_sel.py`, and `tests/test_f16_op_sel_values.py`; also **hardware-verified on RDNA2** (`gfx1035`, Windows 11, driver `26.5.1`, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_min3_max3_med3_16`): all eight ops (`op_sel`, untouched destination half, NaN, −0/+0 ordering, and `v_max3_f16` `clamp`) match bit-for-bit. | | `v_cvt_flr_i32_f32`, `v_cvt_rpi_i32_f32` | RDNA ISA pseudocode: `f32_to_i32(floor(S0))` and `f32_to_i32(floor(S0 + 0.5))`, the `+ 0.5` rounded in binary32 like any f32 add (so 0.49999997 gives 1, where an exact round-half-up would give 0). `f32_to_i32` saturates as in the row above: INT_MAX / INT_MIN at or past ±2³¹ and for ±inf, 0 for NaN. `sat_i32(floor(S0))` and exact `sat_i32(floor(S0 + 0.5))` (computed via `f = Floor(x); (x - f >= 0.5) ? f + 1 : f`, with no binary32 rounding of `S0 + 0.5`: `0x3effffff` → `0`, `0x4b000001` → `0x00800001`, `0x4b7fffff` → `0x00ffffff`). Out-of-range values (±2³¹ and beyond, ±inf) and NaNs all saturate by the sign bit of the operand (`+NaN` → `0x7FFFFFFF`, `-NaN` → `0x80000000`, unlike `v_cvt_i32_f32` which returns `0` for NaN); the sign is read from `x` before `Floor` so driver NaN canonicalization cannot flip it. Source neg/abs apply first. Checked on the CPU by `tests/semantic/test_alu_cvt_flr_rpi.py`, **not yet GPU-verified**. **Until 2026-11-22 the translator rounded `S0 + 0.5` in binary32 and returned `0` for NaN.** Hardware-verified natively on RDNA2 (AMD Radeon 680M `gfx1035`: 82/82 wave32 and 82/82 wave64 via `tools/hw_oracle`, plus `gfx1036` confirmation in #1746) and CPU-checked by `tests/semantic/test_alu_cvt_flr_rpi.py`. | diff --git a/docs/testing.md b/docs/testing.md index 4d76e9f2e8..b0b3dda29c 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -357,6 +357,27 @@ It needs shader Int64 support; a device that lacks it reports a skip. This is a independent of wave64 emulation. On RTX 3080 Ti (616.92, Windows 11), all 640 words matched; replacing the count mask with 31 or the arithmetic shift with a logical shift made the test fail at words 66 and 251 respectively. +`cs_w32_frexp_ldexp` checks `v_frexp_mant_f32`, `v_frexp_exp_i32_f32`, `v_ldexp_f32`, `v_frexp_mant_f64` and +`v_frexp_exp_i32_f64`, which the translator computes with integer ops on the float's words. 64 records of a binary32 +value, an `ldexp` exponent and a binary64 value are loaded at run time: normals, the clamp of the exponent at ±512 +and beyond, results that overflow to an infinity and that fall below the smallest normal, binary32 denormals (read +as zero), binary64 subnormals (normalized; single fraction bits on both sides of the dword boundary and patterns +with several), zeros, infinities and NaNs. Each thread stores the five results, `v_frexp_mant_f32` with a `neg` +source and `v_ldexp_f32` with an `abs` source run with the odd threads turned off, whose destination must keep the +word it held. The expected words come from an oracle written from the rows of [design.md](design.md) +(`frexp_mant_f32`, `frexp_exp_i32_f32`, `ldexp_f32` and `frexp_f64` in `check.py`), and +`tests/test_gpu_frexp_ldexp.py` checks it against `math.frexp` and `math.ldexp` wherever those agree with the +hardware. Both GPU runners compare all 768 heap words, the 256 unchanged input words included. Run it alone with +`python -I scripts/run_gpu_tests.py --build runtime/build --filter cs_w32_frexp_ldexp --require-pass`. +On an RTX 4070 Ti (NVIDIA 620.70.06, Linux) and on llvmpipe (Mesa 26.2.6, LLVM 23.1.4) all 768 words match. While +the binary32 ops still applied `neg` and `abs` with `OpFNegate` and `FAbs`, six words differed on the 4070 Ti and none +on llvmpipe: every NaN source under a modifier came back as `0x7fffffff`, the driver's default NaN (word 419 is the +first: the mantissa of the negated `0x7fc00000`). Rules broken one at a time each failed the test on both devices: +the mantissa given the exponent field 127 (word 0) or, for binary64, 1023 (word 5), the exponent subtracting 127 +(word 1), `v_ldexp_f32` without its clamp (word 258) or overflowing to the largest finite value (word 106), a +binary32 denormal not read as zero (word 352), the binary64 subnormal exponent off by one in the low or in the high +dword (words 134 and 150), and the fixture without its `v_cmpx` (word 15). + `cs_w32_cmp_f64` checks the 32 binary64 vector compares, `v_cmp_*_f64` into VCC and `v_cmpx_*_f64` on EXEC, with 256 memory-fed operand pairs: the product of 16 values (±inf, ±max, the 1-ULP neighbours of ±1, the smallest subnormals, ±0, the smallest normal, a NaN whose payload is only in the low dword and a negative quiet NaN). Each diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py index 3c3f45928c..8725cdcf1a 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py @@ -563,6 +563,116 @@ def round_f64_test(tools, spirv, env=None): return dump_test(tools, spirv, "cs_w32_round_f64", expected, len(expected), child, judge=round_f64_problem) +# cs_w32_frexp_ldexp.asm: per thread a binary32 word with the exponent v_ldexp_f32 adds to it (a 32-bit word, signed), +# and a binary64 pattern. +FREXP_LDEXP_F32 = ( + (0x3F800000, 0), (0x3F800000, 1), (0x3F800000, 0xFFFFFFFF), (0x3FC00000, 10), # 1 and 1.5 + (0xBFC00000, 0xFFFFFFF6), (0x3F7FFFFF, 127), (0x3EAAAAAB, 3), (0xBF400000, 4), # -1.5 by 2^-10, ... + (0x47F12065, 0xFFFFFFEC), (0xC0490FDB, 100), (0x42F6E979, 0xFFFFFF7E), (0x3F000000, 0), # 123456.79 by 2^-20 + (0x3F800000, 127), (0x3F800000, 128), (0x3F800000, 0xFFFFFF82), (0x3F800000, 0xFFFFFF81), # 1 by 2^127 .. 2^-127 + (0x00800000, 0xFFFFFFFF), (0x00800000, 1), (0x00800000, 253), (0x00800000, 254), # the smallest normal + (0x00800001, 0xFFFFFFFF), (0x7F7FFFFF, 1), (0x7F7FFFFF, 0xFFFFFFFF), (0x7F7FFFFF, 0), # the largest finite + (0x7F7FFFFF, 0xFFFFFF03), (0x7F7FFFFF, 0xFFFFFF02), (0xFF7FFFFF, 2), (0x7F000000, 1), # ... by 2^-253, 2^-254 + (0x40000000, 512), (0x40000000, 0xFFFFFE00), (0x40000000, 513), (0x40000000, 0xFFFFFDFF), # the clamp at +-512 + (0x3F800000, 0x7FFFFFFF), (0xBF800000, 0x80000000), (0x00800000, 0x7FFFFFFF), (0x7F7FFFFF, 0x80000000), + (0x3F000000, 0xFFFFFF83), (0x3F000000, 0xFFFFFF82), (0x7F000000, 0), (0x00FFFFFF, 0xFFFFFFFF), + (0x00000000, 5), (0x80000000, 0xFFFFFFFB), (0x00000000, 0x7FFFFFFF), (0x80000000, 0x80000000), # zeros + (0x00000001, 10), (0x807FFFFF, 300), (0x007FFFFF, 0), (0x00400000, 1), # denormals + (0x7F800000, 0xFFFFFFFB), (0xFF800000, 500), (0x7F800000, 0x80000000), (0xFF800000, 0), # infinities + (0x7FC00000, 3), (0x7F800001, 0xFFFFFFFD), (0xFFC12345, 1000), (0xFF800001, 0xFFFFFC18), # NaNs + (0x3F800001, 23), (0xBF7FFFFF, 0xFFFFFFE9), (0x41200000, 0xFFFFFF80), (0x3DCCCCCD, 130), + (0x4B800000, 0xFFFFFF6A), (0x33800000, 150), (0x7EFFFFFF, 1), (0x01000000, 0xFFFFFFFE)) +FREXP_F64 = ( + 0x3FF0000000000000, 0xBFF0000000000000, 0x3FE8000000000000, 0x4008000000000000, # 1, -1, 0.75, 3 + 0x7E37E43C8800759C, 0x01A56E1FC2F8F359, 0x7FEFFFFFFFFFFFFF, 0xFFEFFFFFFFFFFFFF, # 1e300, 1e-300, +-max + 0x0010000000000000, 0x8010000000000000, 0x3FF0000000000001, 0x400921FB54442D18, # +-min normal, 1 + ulp, pi + 0x3FB999999999999A, 0xBFB999999999999A, 0x4330000000000000, 0x0170000000000000, # +-0.1, 2^52, 2^-1000 + 0x0000000000000001, 0x8000000000000001, 0x000FFFFFFFFFFFFF, 0x800FFFFFFFFFFFFF, # subnormals: the smallest, largest + 0x0000000080000000, 0x0000000100000000, 0x0008000000000000, 0x00000001FFFFFFFF, # bit 31, bit 32, bit 51, 33 bits + 0x0000000180000000, 0x000000000000FFFF, 0x8000000100000001, 0x0004000000000001, # bits on both sides of the dwords + 0x0000000000000002, 0x0000000000008000, 0x0000000000010000, 0x0000000040000000, # single bits 1, 15, 16, 30 + 0x0000000200000000, 0x0000800000000000, 0x0001000000000000, 0x0004000000000000, # single bits 33, 47, 48, 50 + 0x800000000000ABCD, 0x80000000FFFFFFFF, 0x8000FFFF00000000, 0x000ABCDEF0123456, + 0x0000000000000000, 0x8000000000000000, 0x7FF0000000000000, 0xFFF0000000000000, # zeros and infinities + 0x7FF8000000000000, 0x7FF0000000000001, 0xFFF8000012345678, 0xFFF0000080000000, # NaNs + 0x3FE0000000000000, 0xBFE0000000000000, 0x7FE0000000000000, 0x0020000000000000, # +-0.5, 2^1023, 2^-1021 + 0x4059000000000000, 0xC08F400000000000, 0x3F50624DD2F1A9FC, 0x41DFFFFFFFC00000, # 100, -1000, 0.001, 2^31 - 1 + 0x3FEFFFFFFFFFFFFF, 0xBFEFFFFFFFFFFFFF, 0x001FFFFFFFFFFFFF, 0x801FFFFFFFFFFFFF, + 0x43E0000000000000, 0xC3E0000000000000, 0x3CA0000000000000, 0x7FD0000000000001) +FREXP_LDEXP_KEPT = 0xDEADBEEF # the word an inactive lane keeps + + +def frexp_mant_f32(x): + """v_frexp_mant_f32 on a binary32 word (docs/design.md): a normal keeps its sign and fraction and gets the + exponent field 126; a zero or a denormal, read as zero, gives a zero of its sign; an infinity or a NaN comes + back unchanged.""" + exponent = x >> 23 & 0xFF + if exponent == 0: + return x & 0x80000000 + return x if exponent == 255 else x & 0x807FFFFF | 126 << 23 + + +def frexp_exp_i32_f32(x): + """v_frexp_exp_i32_f32: the exponent field minus 126 for a normal, as a 32-bit word; 0 for everything else.""" + exponent = x >> 23 & 0xFF + return (exponent - 126) & 0xFFFFFFFF if 0 < exponent < 255 else 0 + + +def ldexp_f32(x, n): + """v_ldexp_f32: the 32-bit word n, read as signed and clamped to [-512, 512], is added to the exponent field of + a normal x. A field above 254 gives an infinity of x's sign and one of 0 or below a zero of its sign (there are + no denormal results). A zero or a denormal gives a zero of its sign, and an infinity or a NaN comes back.""" + exponent, sign = x >> 23 & 0xFF, x & 0x80000000 + if exponent == 0: + return sign + if exponent == 255: + return x + exponent += max(-512, min(512, n - (1 << 32) if n & 0x80000000 else n)) + if exponent > 254: + return sign | 0x7F800000 + return sign if exponent <= 0 else x & 0x807FFFFF | exponent << 23 + + +def frexp_f64(bits): + """(v_frexp_mant_f64, v_frexp_exp_i32_f64) of a binary64 pattern, the exponent as a 32-bit word. A normal gets + the exponent field 1022 and gives its field minus 1022. A subnormal is normalized: its top fraction bit, at + position p, becomes the implicit one, and the exponent is p - 1073. A zero keeps its sign and an infinity or a + NaN comes back unchanged, all three with exponent 0.""" + exponent, fraction, sign = bits >> 52 & 0x7FF, bits & ((1 << 52) - 1), bits & (1 << 63) + if exponent == 0x7FF: + return bits, 0 + if exponent: + return sign | 1022 << 52 | fraction, (exponent - 1022) & 0xFFFFFFFF + if not fraction: + return sign, 0 + top = fraction.bit_length() - 1 + return sign | 1022 << 52 | (fraction << (52 - top)) & ((1 << 52) - 1), (top - 1073) & 0xFFFFFFFF + + +def frexp_ldexp_words(): + """cs_w32_frexp_ldexp: the input heap and the full expected readback, eight result words per thread and then + the records {x, n, d.lo, d.hi}.""" + results, inputs = [], [] + for thread, ((x, n), d) in enumerate(zip(FREXP_LDEXP_F32, FREXP_F64)): + mantissa, exponent = frexp_f64(d) + results.extend((frexp_mant_f32(x), frexp_exp_i32_f32(x), ldexp_f32(x, n), frexp_mant_f32(x ^ 0x80000000), + mantissa & 0xFFFFFFFF, mantissa >> 32, exponent, + ldexp_f32(x & 0x7FFFFFFF, n) if thread % 2 == 0 else FREXP_LDEXP_KEPT)) + inputs.extend((x, n, d & 0xFFFFFFFF, d >> 32)) + return [0xEEEEEEEE] * len(results) + inputs, results + inputs + + +def frexp_ldexp_test(tools, spirv, env=None): + """Verify the five frexp and ldexp ops on 64 memory-fed records, including the untouched input records.""" + initial, expected = frexp_ldexp_words() + with tempfile.TemporaryDirectory(prefix="leonida-frexp-ldexp-") as tmp: + path = Path(tmp) / "input.bin" + path.write_bytes(struct.pack(f"<{len(initial)}I", *initial)) + child = dict(os.environ if env is None else env, VKC_HEAP_INIT=str(path)) + child.setdefault("VKC_SUBGROUP_SIZE", str(subgroup_size(spirv, "cs_w32_frexp_ldexp") or 32)) + return dump_test(tools, spirv, "cs_w32_frexp_ldexp", expected, len(expected), child) + + # cs_user_sgprs.asm: vk_compute_test puts these words in s4..s7 and the shader stores them back. USER_SGPRS = [0x4F000000, 0xDEADBEEF, 7, 0xFFFFFFFF] USER_SGPRS_ENV = {"VKC_SGPRS": ",".join(hex(w) for w in USER_SGPRS)} @@ -2064,6 +2174,7 @@ def main(): results.append(("cs_w32_shift64", shift64_test(tools, spirv))) results.append(("cs_w32_cmp_f64", cmp_f64_test(tools, spirv))) results.append(("cs_w32_round_f64", round_f64_test(tools, spirv))) + results.append(("cs_w32_frexp_ldexp", frexp_ldexp_test(tools, spirv))) results.append(("cs_cvt_f32_sat", cvt_f32_sat_test(tools, spirv))) results.append(("cs_fma_fused", fma_fused_test(tools, spirv))) results.append(("cs_cvt_pk_u8", compute_test(tools, spirv, "cs_cvt_pk_u8", "1", "dump", diff --git a/runtime/test/shaders/cs_w32_frexp_ldexp.asm b/runtime/test/shaders/cs_w32_frexp_ldexp.asm new file mode 100644 index 0000000000..330549eb1b --- /dev/null +++ b/runtime/test/shaders/cs_w32_frexp_ldexp.asm @@ -0,0 +1,44 @@ +; GPU-FREXP-LDEXP: v_frexp_mant_f32, v_frexp_exp_i32_f32, v_ldexp_f32, v_frexp_mant_f64 and v_frexp_exp_i32_f64. +; group: 64,1,1 +; mattr: +wavefrontsize32,-wavefrontsize64 +; check.py seeds 64 records at byte 0x800: {x, n, d.lo, d.hi}, a binary32 value, an ldexp exponent and a binary64 +; value. Thread i reads record i from memory, so neither the translator nor the driver can fold an op, and writes +; eight words at byte 32 * i: +; +0 v_frexp_mant_f32 x a normal keeps sign and fraction and gets the exponent field 126 (a mantissa +; in [0.5, 1)); a zero or a denormal, read as zero, gives a zero of its sign; +; an infinity or a NaN comes back unchanged +; +4 v_frexp_exp_i32_f32 x the exponent field minus 126 for a normal, 0 for everything else +; +8 v_ldexp_f32 x, n n is clamped to [-512, 512] and added to the exponent field: above 254 the +; result is an infinity of x's sign, at 0 or below a zero of its sign (there +; are no denormal results); a zero, a denormal, an infinity and a NaN ignore n +; +12 v_frexp_mant_f32 -x VOP3 neg: the sign bit is flipped first +; +16 v_frexp_mant_f64 d two words, low first: a normal gets the exponent field 1022; a subnormal is +; normalized into [0.5, 1) too; a zero keeps its sign; an infinity or a NaN +; comes back unchanged +; +24 v_frexp_exp_i32_f64 d the exponent field minus 1022 for a normal, the position of the top fraction +; bit minus 1073 for a subnormal (-1073..-1022), 0 for everything else +; +28 v_ldexp_f32 |x|, n VOP3 abs, with the odd threads turned off first: they keep the 0xdeadbeef +; that was in the destination +; The records cover normals, the clamp of n at +-512 and beyond, results that overflow and that fall below the +; smallest normal, binary32 denormals, binary64 subnormals with single bits on both sides of the dword boundary and +; with several bits, zeros, infinities and NaNs. The rules are the rows of docs/design.md for these five ops. +; The input records must come back unchanged. +; Run with the heap initialized by check.py's frexp_ldexp_test; compare all 768 words. +v_lshlrev_b32_e32 v1, 4, v0 +v_lshlrev_b32_e32 v10, 5, v0 +v_and_b32_e32 v9, 1, v0 +buffer_load_dwordx4 v[2:5], v1, s[0:3], 0 offen offset:2048 +s_waitcnt vmcnt(0) +v_frexp_mant_f32_e32 v12, v2 +v_frexp_exp_i32_f32_e32 v13, v2 +v_ldexp_f32 v14, v2, v3 +v_frexp_mant_f32_e64 v15, -v2 +v_frexp_mant_f64_e32 v[16:17], v[4:5] +v_frexp_exp_i32_f64_e32 v18, v[4:5] +v_mov_b32_e32 v19, 0xdeadbeef +v_cmpx_eq_u32_e32 0, v9 +v_ldexp_f32 v19, |v2|, v3 +s_mov_b32 exec_lo, -1 +buffer_store_dwordx4 v[12:15], v10, s[0:3], 0 offen +buffer_store_dwordx4 v[16:19], v10, s[0:3], 0 offen offset:16 +s_endpgm diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index aac6efeeed..180c9773ae 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -39,6 +39,7 @@ 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 +from check import frexp_ldexp_test # binary32 and binary64 frexp, and v_ldexp_f32, on memory-fed records from check import judged_words, words_match # dump words not judged on some devices (cs_signed_zero_nan) from check import TEXOFF_ARGS, texoff_problem # ps_texoff's expected words and arguments live in check.py from check import TEXOFF_FALLBACK, texoff_env # LEONIDA_TEXOFF_FALLBACK=1: texel offsets without maintenance8 @@ -985,6 +986,10 @@ def run_suite(a, work: str) -> int: if name in CLIP_CASES: detail = clip_test(a.build, spirv_dir, name) results.append((name, None if isinstance(detail, Skip) else not detail, detail or "four pixel masks exact")) + elif name == "cs_w32_frexp_ldexp": + detail = frexp_ldexp_test(a.build, spirv_dir, cs_env) + results.append((name, None if isinstance(detail, Skip) else not detail, + detail or "768 words exact (64 records, eight results each, and unchanged inputs)")) elif name == "cs_w32_shift64": detail = shift64_test(a.build, spirv_dir, cs_env) results.append((name, None if isinstance(detail, Skip) else not detail, diff --git a/tests/semantic/test_alu_frexp_ldexp.py b/tests/semantic/test_alu_frexp_ldexp.py index 226459728f..e7877f44c9 100644 --- a/tests/semantic/test_alu_frexp_ldexp.py +++ b/tests/semantic/test_alu_frexp_ldexp.py @@ -83,6 +83,18 @@ def run(line: str, v1: int, v2: int = 0) -> int: return si.run_fragment(spv)["%out_mrt0"][0] +def translated(line: str) -> str: + """The SPIR-V text of a pixel shader that runs ``line`` on v1 and v2 and exports v0.""" + if _TMP_DIR is None: + setUpModule() + asm = f"; test_frexp_ldexp\n\t{line}\n\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" + with open(_SRC_PATH, "w", encoding="utf-8", newline="\n") as f: + f.write(asm) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ResourceWarning) + return rdna2spirv.translate(_SRC_PATH) + + def ref_mant(u: int) -> int: if not is_normal(u): return (u & 0x80000000) if (u >> 23) & 0xFF == 0 else u @@ -205,5 +217,53 @@ def test_source_and_output_modifiers(self): self.assertEqual(run("v_ldexp_f32_e64 v0, v1, v2 clamp", f2u(1.0), 3), f2u(1.0)) +class SourceModifierBitsTests(unittest.TestCase): + """abs and neg on the float source of the three ops move its sign bit and nothing else (SHADER-FREXP-LDEXP- + SIGN-MODS). Through FAbs/OpFNegate a driver may return any NaN for a NaN: an RTX 4070 Ti gave 0x7fffffff for + every NaN source (cs_w32_frexp_ldexp). The interpreter negates on the bits either way, so the values below hold + with both lowerings and it is the missing float instructions that tell them apart.""" + FORMS = ("v_frexp_mant_f32_e64 v0, -v1", "v_frexp_mant_f32_e64 v0, |v1|", "v_frexp_mant_f32_e64 v0, -|v1|", + "v_frexp_exp_i32_f32_e64 v0, -v1", "v_frexp_exp_i32_f32_e64 v0, |v1|", + "v_ldexp_f32_e64 v0, -v1, v2", "v_ldexp_f32_e64 v0, |v1|, v2", "v_ldexp_f32_e64 v0, -|v1|, v2") + + def test_the_modifiers_are_not_float_instructions(self): + for line in self.FORMS: + with self.subTest(line=line): + text = translated(line) + self.assertNotIn("OpFNegate", text) + self.assertNotIn("FAbs", text) + self.assertIn("OpBitwiseXor" if "-" in line else "OpBitwiseAnd", text) + + def test_the_check_above_tells_the_two_lowerings_apart(self): + # An op that computes with its source still negates the float. + self.assertIn("OpFNegate", translated("v_add_f32_e64 v0, -v1, v2")) + self.assertIn("FAbs", translated("v_add_f32_e64 v0, |v1|, v2")) + # And without a modifier the three ops emit neither instruction nor a sign-bit move. + for line in ("v_frexp_mant_f32_e32 v0, v1", "v_ldexp_f32_e64 v0, v1, v2"): + self.assertNotIn("OpFNegate", translated(line)) + + def test_a_nan_keeps_its_payload_under_a_modifier(self): + cases = ((0x7FC00000, 0xFFC00000, 0x7FC00000), (0x7F800001, 0xFF800001, 0x7F800001), + (0xFFC12345, 0x7FC12345, 0x7FC12345), (0xFF800001, 0x7F800001, 0x7F800001)) + for u, negated, magnitude in cases: + with self.subTest(u=hex(u)): + self.assertEqual(run("v_frexp_mant_f32_e64 v0, -v1", u), negated) + self.assertEqual(run("v_frexp_mant_f32_e64 v0, |v1|", u), magnitude) + self.assertEqual(run("v_frexp_mant_f32_e64 v0, -|v1|", u), magnitude | 0x80000000) + self.assertEqual(run("v_ldexp_f32_e64 v0, -v1, v2", u, 5), negated) + self.assertEqual(run("v_ldexp_f32_e64 v0, |v1|, v2", u, 0xFFFFFFFB), magnitude) + self.assertEqual(run("v_frexp_exp_i32_f32_e64 v0, -v1", u), 0) + + def test_zeros_denormals_and_infinities_take_the_moved_sign(self): + for u in (0x00000000, 0x80000000, 0x00000001, 0x807FFFFF): # a denormal is read as a zero of its sign + with self.subTest(u=hex(u)): + self.assertEqual(run("v_frexp_mant_f32_e64 v0, -v1", u), (u ^ 0x80000000) & 0x80000000) + self.assertEqual(run("v_frexp_mant_f32_e64 v0, |v1|", u), 0) + self.assertEqual(run("v_ldexp_f32_e64 v0, -|v1|, v2", u, 40), 0x80000000) + self.assertEqual(run("v_frexp_mant_f32_e64 v0, -v1", INF), NINF) + self.assertEqual(run("v_ldexp_f32_e64 v0, |v1|, v2", NINF, 7), INF) + self.assertEqual(run("v_ldexp_f32_e64 v0, -v1, v2", f2u(1.5), 0xFFFFFFFF), f2u(-0.75)) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_gpu_frexp_ldexp.py b/tests/test_gpu_frexp_ldexp.py new file mode 100644 index 0000000000..c6a5cbf80c --- /dev/null +++ b/tests/test_gpu_frexp_ldexp.py @@ -0,0 +1,236 @@ +"""GPU-FREXP-LDEXP: the frexp and ldexp oracle, the readback and the runner verdicts, without needing a GPU.""" +import contextlib +import io +import math +from pathlib import Path +import struct +import sys +import tempfile +from types import SimpleNamespace +import unittest +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "scripts")) +import run_gpu_tests as rgt +import check + +WORDS = 768 # 64 threads of eight result words, then 64 records of four input words +RESULTS = 512 +FIXTURE = ROOT / "runtime" / "test" / "shaders" / "cs_w32_frexp_ldexp.asm" + + +def f32(bits): + return struct.unpack("> 23 & 0xFF + if exponent == 0: + return "denormal" if bits & 0x007FFFFF else "zero" + if exponent == 255: + return "nan" if bits & 0x007FFFFF else "inf" + return "normal" + + +class FrexpLdexpOracle(unittest.TestCase): + def test_records_cover_the_classes_the_fixture_names(self): + self.assertEqual((len(check.FREXP_LDEXP_F32), len(set(check.FREXP_LDEXP_F32))), (64, 64)) + self.assertEqual((len(check.FREXP_F64), len(set(check.FREXP_F64))), (64, 64)) + kinds = [kind32(x) for x, _ in check.FREXP_LDEXP_F32] + self.assertEqual({k: kinds.count(k) for k in sorted(set(kinds))}, + {"denormal": 4, "inf": 4, "nan": 4, "normal": 48, "zero": 4}) + exponents = {signed(n) for _, n in check.FREXP_LDEXP_F32} + self.assertTrue({512, -512, 513, -513, 0x7FFFFFFF, -0x80000000, 0, 1, -1} <= exponents) + doubles = check.FREXP_F64 + subnormal = [d for d in doubles if d >> 52 & 0x7FF == 0 and d & ((1 << 52) - 1)] + self.assertEqual(len(subnormal), 24) + # Single fraction bits on both sides of the dword boundary, and patterns with bits in both dwords. + self.assertTrue({1 << 31, 1 << 32, 1, 1 << 51} <= set(subnormal)) + self.assertTrue(any(d & 0xFFFFFFFF and d >> 32 & 0xFFFFF for d in subnormal)) + self.assertEqual(sum(math.isnan(f64(d)) for d in doubles), 4) + self.assertEqual(sum(math.isinf(f64(d)) for d in doubles), 2) + + def test_binary32_normals_agree_with_python(self): + """math.frexp and math.ldexp work on the double value of a binary32 normal, exactly. They agree with the + hardware wherever its result is a normal; outside that the hardware saturates to an infinity or a zero.""" + compared = 0 + for x, n in check.FREXP_LDEXP_F32: + if kind32(x) != "normal": + continue + mantissa, exponent = math.frexp(f32(x)) + self.assertEqual(check.frexp_mant_f32(x), f32_bits(mantissa), hex(x)) + self.assertEqual(signed(check.frexp_exp_i32_f32(x)), exponent, hex(x)) + field = (x >> 23 & 0xFF) + max(-512, min(512, signed(n))) + got = check.ldexp_f32(x, n) + if field > 254: + self.assertEqual(got, x & 0x80000000 | 0x7F800000, (hex(x), n)) + elif field <= 0: + self.assertEqual(got, x & 0x80000000, (hex(x), n)) + else: + self.assertEqual(got, f32_bits(math.ldexp(f32(x), signed(n))), (hex(x), n)) + compared += 1 + self.assertGreaterEqual(compared, 16) + + def test_binary64_finite_values_agree_with_python(self): + """math.frexp normalizes a subnormal as the hardware does, so every finite non-zero pattern is compared.""" + compared = 0 + for d in check.FREXP_F64: + value = f64(d) + if value == 0 or math.isinf(value) or math.isnan(value): + continue + mantissa, exponent = math.frexp(value) + self.assertEqual(check.frexp_f64(d), (f64_bits(mantissa), exponent & 0xFFFFFFFF), hex(d)) + self.assertEqual(math.ldexp(f64(check.frexp_f64(d)[0]), signed(check.frexp_f64(d)[1])), value) + compared += 1 + self.assertEqual(compared, 56) + + def test_values_the_contract_rows_name(self): + # Zero and denormals give a signed zero and exponent 0; infinities and NaNs the input and exponent 0. + for x in (0x00000000, 0x80000000, 0x00000001, 0x807FFFFF): + self.assertEqual((check.frexp_mant_f32(x), check.frexp_exp_i32_f32(x)), (x & 0x80000000, 0)) + self.assertEqual(check.ldexp_f32(x, 300), x & 0x80000000) + for x in (0x7F800000, 0xFF800000, 0x7FC00000, 0x7F800001, 0xFFC12345): + self.assertEqual((check.frexp_mant_f32(x), check.frexp_exp_i32_f32(x)), (x, 0)) + self.assertEqual(check.ldexp_f32(x, 0xFFFFFFFB), x) + one, two = f32_bits(1.0), f32_bits(2.0) + self.assertEqual((check.frexp_mant_f32(one), check.frexp_exp_i32_f32(one)), (f32_bits(0.5), 1)) + self.assertEqual(check.ldexp_f32(one, 127), f32_bits(2.0 ** 127)) + self.assertEqual(check.ldexp_f32(one, 128), 0x7F800000) # above the exponent field 254 + self.assertEqual(check.ldexp_f32(one, 0xFFFFFF82), 0x00800000) # 2^-126, the smallest normal + self.assertEqual(check.ldexp_f32(one, 0xFFFFFF81), 0) # 2^-127: no denormal result + self.assertEqual(check.ldexp_f32(two, 513), check.ldexp_f32(two, 512)) # the clamp + self.assertEqual(check.ldexp_f32(0x00800000, 0x7FFFFFFF), 0x7F800000) + self.assertEqual(check.ldexp_f32(0x7F7FFFFF, 0x80000000), 0) + self.assertEqual(check.ldexp_f32(0x7F7FFFFF, 0xFFFFFF03), 0x00FFFFFF) # field 254 - 253 = 1 + # The two subnormals the binary64 row gives. + self.assertEqual(check.frexp_f64(0x0000000000000001), (0x3FE0000000000000, (-1073) & 0xFFFFFFFF)) + self.assertEqual(check.frexp_f64(0x000FFFFFFFFFFFFF), (0x3FEFFFFFFFFFFFFE, (-1022) & 0xFFFFFFFF)) + for d in (0x0000000000000000, 0x8000000000000000, 0x7FF0000000000000, 0xFFF0000000000000, + 0x7FF0000000000001, 0xFFF8000012345678): + self.assertEqual(check.frexp_f64(d), (d, 0)) + + def test_layout(self): + initial, expected = check.frexp_ldexp_words() + self.assertEqual((len(initial), len(expected)), (WORDS, WORDS)) + self.assertEqual(initial[:RESULTS], [0xEEEEEEEE] * RESULTS) + self.assertEqual(initial[RESULTS:], expected[RESULTS:]) + # Thread 0: x = 1, n = 0, d = 1. Mantissa 0.5, exponent 1, ldexp 1, mantissa of -1, the binary64 pair, its + # exponent, and (an even thread) ldexp of |1|. + self.assertEqual(expected[:8], [0x3F000000, 1, 0x3F800000, 0xBF000000, 0, 0x3FE00000, 1, 0x3F800000]) + self.assertEqual(expected[RESULTS:RESULTS + 4], [0x3F800000, 0, 0, 0x3FF00000]) + # Thread 53 holds the signalling NaN 0x7f800001 and is odd: mantissa unchanged, exponent 0, ldexp unchanged, + # the mantissa of its negation, and the word its inactive lane keeps. + self.assertEqual(check.FREXP_LDEXP_F32[53], (0x7F800001, 0xFFFFFFFD)) + self.assertEqual(expected[8 * 53:8 * 53 + 4], [0x7F800001, 0, 0x7F800001, 0xFF800001]) + self.assertEqual(expected[8 * 53 + 7], 0xDEADBEEF) + # Thread 54 is even: ldexp of |0xffc12345| is the NaN without its sign. + self.assertEqual(expected[8 * 54 + 7], 0x7FC12345) + + +class FrexpLdexpFixture(unittest.TestCase): + def test_assembly_stores_the_eight_words_the_oracle_lists(self): + lines = [ln.strip() for ln in FIXTURE.read_text(encoding="utf-8").splitlines()] + code = [ln for ln in lines if ln and not ln.startswith(";")] + self.assertIn("; group: 64,1,1", lines) + self.assertEqual(code, [ + "v_lshlrev_b32_e32 v1, 4, v0", "v_lshlrev_b32_e32 v10, 5, v0", "v_and_b32_e32 v9, 1, v0", + "buffer_load_dwordx4 v[2:5], v1, s[0:3], 0 offen offset:2048", "s_waitcnt vmcnt(0)", + "v_frexp_mant_f32_e32 v12, v2", "v_frexp_exp_i32_f32_e32 v13, v2", "v_ldexp_f32 v14, v2, v3", + "v_frexp_mant_f32_e64 v15, -v2", + "v_frexp_mant_f64_e32 v[16:17], v[4:5]", "v_frexp_exp_i32_f64_e32 v18, v[4:5]", + "v_mov_b32_e32 v19, 0xdeadbeef", "v_cmpx_eq_u32_e32 0, v9", "v_ldexp_f32 v19, |v2|, v3", + "s_mov_b32 exec_lo, -1", + "buffer_store_dwordx4 v[12:15], v10, s[0:3], 0 offen", + "buffer_store_dwordx4 v[16:19], v10, s[0:3], 0 offen offset:16", + "s_endpgm"]) + self.assertEqual(check.FREXP_LDEXP_KEPT, 0xDEADBEEF) + + +class FrexpLdexpReadback(unittest.TestCase): + def run_readback(self, mutate=None, code=0, output="", missing=False): + paths = [] + + def launch(*args, env): + paths.append(Path(env["VKC_HEAP_INIT"])) + initial, expected = check.frexp_ldexp_words() + self.assertEqual(args[1:], (str(Path("unused") / "cs_w32_frexp_ldexp.spv"), "1", "dump")) + self.assertEqual(paths[-1].read_bytes(), struct.pack(f"<{WORDS}I", *initial)) + self.assertEqual(env["VKC_SUBGROUP_SIZE"], "32") + self.assertEqual(env["VKC_OUT_WORDS"], str(WORDS)) + self.assertEqual(env["LEONIDA_VK_DEVICE"], "synthetic device") + if mutate: + mutate(expected) + if not missing: + Path(env["VKC_DUMP"]).write_bytes(struct.pack(f"<{len(expected)}I", *expected)) + return code, output + + with patch.object(check, "run", side_effect=launch): + result = check.frexp_ldexp_test("unused", "unused", {"LEONIDA_VK_DEVICE": "synthetic device"}) + self.assertEqual(len(paths), 1) + self.assertFalse(paths[0].exists(), "private heap input must be cleaned up") + return result + + def test_complete_readback_passes(self): + self.assertEqual(self.run_readback(), "") + + def test_one_wrong_word_or_a_changed_input_fails(self): + # Word 419 is the one an RTX 4070 Ti got wrong before the sign-bit modifiers: thread 52, the mantissa of a + # negated NaN. + for index in (0, 419, RESULTS - 1, RESULTS, WORDS - 1): + with self.subTest(word=index): + result = self.run_readback(lambda data: data.__setitem__(index, data[index] ^ 0x00400000)) + self.assertIn(f"word {index}:", result) + self.assertIn("word 419: expected 0xffc00000, got 0x7fffffff", + self.run_readback(lambda data: data.__setitem__(419, 0x7FFFFFFF))) + + def test_truncated_and_missing_dump_fail(self): + self.assertIn(f"expected {4 * WORDS} dump bytes, got {4 * WORDS - 4}", + self.run_readback(lambda data: data.pop())) + self.assertIn("no VKC_DUMP", self.run_readback(missing=True)) + + def test_unsupported_module_skips_but_nonzero_exit_fails(self): + self.assertIsInstance(self.run_readback(code=77, output="unsupported: no Int64\n"), check.Skip) + self.assertIn("exit 1", self.run_readback(code=1, output="dispatch failed")) + + +class FrexpLdexpRunner(unittest.TestCase): + def test_filtered_runner_counts_pass_failure_and_skip(self): + for detail, expected, verdict in (("", 0, "1/1 passed"), ("word 419: mismatch", 1, "0/1 passed"), + (check.Skip("SKIP (no Int64)"), 0, "0/1 passed, 1 skipped")): + with self.subTest(detail=detail), tempfile.TemporaryDirectory() as tmp: + args = SimpleNamespace(filter="cs_w32_frexp_ldexp", build=tmp, llvm_mc="unused") + + def translate(_cmd, **_kwargs): + (Path(tmp) / "spirv" / "cs_w32_frexp_ldexp.spv").touch() + return 0, "" + + output = io.StringIO() + with (patch.object(rgt, "assemble_to_s", side_effect=lambda _mc, _src, dst, _name: Path(dst).touch()), + patch.object(rgt, "spirv_as"), patch.object(rgt, "run_cmd", side_effect=translate), + patch.object(rgt, "frexp_ldexp_test", return_value=detail) as readback, + contextlib.redirect_stdout(output)): + self.assertEqual(rgt.run_suite(args, tmp), expected) + readback.assert_called_once() + self.assertIn(verdict, output.getvalue()) + self.assertIn("cs_w32_frexp_ldexp", output.getvalue()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_shader_checks.py b/tests/test_shader_checks.py index 5557362a9f..22e1de35f9 100644 --- a/tests/test_shader_checks.py +++ b/tests/test_shader_checks.py @@ -36,9 +36,9 @@ + 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) + 19) # three mesh fixtures, ps_tex, ps_imgatomic, ps_table_fetch, six compute fixtures, + + len(check.TEXTURE_CONSTANTS) + 20) # three mesh fixtures, ps_tex, ps_imgatomic, ps_table_fetch, six compute fixtures, # ps_ssharp, vs_base_ids, main's standalone cs_fmt_d16_xyz / cs_heap_init dumps (net one more case), cs_fmt_all, - # cs_w32_shift64, cs_w32_cmp_f64 and cs_w32_round_f64 + # cs_w32_shift64, cs_w32_cmp_f64, cs_w32_round_f64 and cs_w32_frexp_ldexp CVT = {bits: [u, s] for bits, u, s in check.CVT_F32_SAT_CASES} @@ -113,6 +113,14 @@ def harness(_tool, shader, *args, env=None): words = expected if seeded else initial Path(env["VKC_DUMP"]).write_bytes(struct.pack(f"<{len(words)}I", *words)) return 0, "" + if name == "cs_w32_frexp_ldexp": + # The frexp and ldexp words come back only if check.py seeded the records through VKC_HEAP_INIT. + initial, expected = check.frexp_ldexp_words() + self.assertEqual((args, env["VKC_OUT_WORDS"]), (("1", "dump"), str(len(expected)))) + seeded = Path(env["VKC_HEAP_INIT"]).read_bytes() == struct.pack(f"<{len(initial)}I", *initial) + words = expected if seeded else initial + Path(env["VKC_DUMP"]).write_bytes(struct.pack(f"<{len(words)}I", *words)) + return 0, "" if name == "cs_w32_round_f64": # The rounded words come back only if check.py seeded the inputs through VKC_HEAP_INIT. initial, expected = check.round_f64_words() diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 8d91dac70e..ae57b27d86 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -11590,7 +11590,9 @@ def f64(sv): # zero and denormals are read as zero (the f32 denormal mode is not modelled, as for the other float ops) # and infinities and NaNs (exponent 255) pass through: frexp_mant and ldexp return S0 unchanged, # frexp_exp returns 0 (RDNA2 ISA, V_FREXP_MANT_F32 / V_FREXP_EXP_I32_F32 / V_LDEXP_F32). - x = self.src_u(a[1]) + # The three ops only move bits, so abs/neg move the sign bit of the raw word: through FAbs/OpFNegate a + # NaN source came back as the driver's default NaN (0x7fffffff on an RTX 4070 Ti, NVIDIA 620.70.06). + x = self.src_u_sign_mods(a[1]) e, em1, isnorm, isden, sgn, r = (self.tmp() for _ in range(6)) self.emit(f"{e} = OpBitFieldUExtract %uint {x} {self.cu(23)} {self.cu(8)}") self.emit(f"{em1} = OpISub %uint {e} {self.cu(1)}") From 60c2ed910b90aef3cf5af1df2366a28a25afbe64 Mon Sep 17 00:00:00 2001 From: milk4sale <53350507+milk4sale@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:54:14 -0600 Subject: [PATCH 3/3] tests: cs_w32_round_f64 allows llvmpipe's float path for Trunc and RoundEven (GPU-ROUND-F64) linux-gpu-tools failed this fixture with `word 164 (thread 10): rndne of 0x3fe0000000000001 gave 0x0000000000000000`, on some runners and not on others. The cause is llvmpipe, not the translation: its double vectors are twice its native width (512 bits at the usual 256), and it has the exact Trunc and RoundEven only for a width the CPU has a vector extension for. Without AVX-512 the two ops go through the code it has for a float, where a magnitude above 2^24 comes back unchanged and RoundEven of a smaller one can give the other neighbouring integer. That is 48 of the 512 results, the same 48 with Mesa 25.2.8 (LLVM 20.1.2) on a runner and with Mesa 26.2.6 (LLVM 23.1.4) under GALLIUM_OVERRIDE_CPU_CAPS=avx, sse4.1 or sse2 on a Ryzen 9 7900X; Floor and Ceil are exact on that path, and with AVX-512 (or AVX at LP_NATIVE_VECTOR_WIDTH=128) so are all four. On llvmpipe the judge now lets v_trunc_f64 and v_rndne_f64 return what that path can give: the source itself above 2^24, either neighbouring integer with the source's sign from 0.5 up to it. Everything else stays exact there, and no other device gets the allowance (ROUND_F64_FLOAT_PATH, keyed like UNJUDGED_WORDS). dump_test hands the test program's output to a judge, for its device line. Tested: the fixture passes on llvmpipe natively and under each of the three overrides, at LP_NATIVE_VECTOR_WIDTH=128, and on the RTX 4070 Ti (NVIDIA 620.70.06) natively and with LEONIDA_W64_EMULATE=1; the previous judge fails under each override at word 164. tests/test_gpu_round_f64.py rebuilds the 48 measured results and checks that nothing wider passes. Co-Authored-By: Claude Fable 5.2 --- docs/testing.md | 13 ++++++ runtime/test/shaders/check.py | 47 +++++++++++++++++---- tests/test_gpu_round_f64.py | 77 ++++++++++++++++++++++++++++++++++- 3 files changed, 127 insertions(+), 10 deletions(-) diff --git a/docs/testing.md b/docs/testing.md index 4d76e9f2e8..a3602037f7 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -397,6 +397,19 @@ of -1. Rules broken one at a time each failed the test on both devices: `rndne` 26), the low result word taken from the high one (word 8), and the fixture without its `v_cmpx` (word 30). Replacing `RoundEven` by GLSL `Round` changed nothing on either device: both send a tie to the even integer. +llvmpipe gave those results on a CPU with AVX-512. On one without it, `Trunc` and `RoundEven` of a double go through +the code llvmpipe has for a float, because its double vectors are twice its native width (512 bits at the usual 256) +and it only has the exact rounding for a width the CPU has an extension for. There a magnitude above 2^24 comes back +unchanged (`v_trunc_f64` of 123456789.0625 is 123456789.0625) and `RoundEven` of a smaller one can give the other +neighbouring integer (1 for 1.5, 0 for the value just above 0.5): 48 of the 512 results, the same 48 with Mesa +25.2.8 (LLVM 20.1.2) on a CI runner and with Mesa 26.2.6 under `GALLIUM_OVERRIDE_CPU_CAPS=avx`, which is how to see +it on a CPU that has AVX-512. `Floor` and `Ceil` are exact on that path. The CI's runners differ in this, so the +unchanged fixture passed or failed there by the machine it got. On llvmpipe the judge therefore lets `v_trunc_f64` +and `v_rndne_f64` return what that path can give, the source itself above 2^24 and either neighbouring integer +from 0.5 up to it, and nothing else (`ROUND_F64_FLOAT_PATH` in `check.py`); `v_floor_f64`, `v_ceil_f64`, the kept +pair and the inputs stay exact there, and no other device gets the allowance. `LP_NATIVE_VECTOR_WIDTH=128` makes +llvmpipe exact on a CPU with AVX. + ## Wave64 pixel, vertex and geometry shaders (`w64_graphics.py`) Graphics stages have no emulation: on a 32-wide subgroup a wave64 VS, PS or GS runs as two 32-lane halves, and the diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py index 3c3f45928c..279b995b02 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py @@ -528,13 +528,42 @@ def round_f64_words(): return [0xEEEEEEEE] * len(results) + inputs, results + inputs -def round_f64_problem(got): - """Judge a readback of cs_w32_round_f64: "" or the first word that is wrong. Every result is exact except for - the two kinds of source Vulkan leaves to the driver's double-precision rounding: a NaN may come back as any NaN - (a signalling one comes back quiet on the drivers measured), and a subnormal may be read as a zero of its sign, - because the module does not declare DenormPreserve for 64 bits.""" +# Drivers that round a binary64 with code written for a binary32, by the first word of the device name on +# vk_compute_test's "device: ..." line (as UNJUDGED_WORDS is keyed), and the ops they do it for. +# - Mesa llvmpipe: Trunc and RoundEven of a double take its float fallback whenever the CPU has no vector extension +# as wide as its double vectors, which are twice its native width: 512 bits at the usual 256, so every CPU without +# AVX-512. There a magnitude above 2^24 comes back unchanged (trunc of 123456789.0625 is 123456789.0625), and +# RoundEven of a smaller one can be the other neighbouring integer (1 for 1.5, 0 for the value just above 0.5). +# Floor and Ceil are exact on that path. Measured with Mesa 25.2.8 (LLVM 20.1.2) on the CI's runners, where the +# CPU decides from run to run, and with Mesa 26.2.6 (LLVM 23.1.4) under GALLIUM_OVERRIDE_CPU_CAPS=avx: 48 of the +# 512 results. With AVX-512, or with AVX at LP_NATIVE_VECTOR_WIDTH=128, all four ops are exact. +ROUND_F64_FLOAT_PATH = {"llvmpipe": ("trunc", "rndne")} + + +def round_f64_float_path(op, source, value): + """Whether `value` is what a driver in ROUND_F64_FLOAT_PATH may give for the rounding of the finite `source` + instead of round_f64's word: the source itself when its magnitude is above 2^24, else one of its two + neighbouring integers, with the source's sign. Nothing below 0.5, a subnormal included: Trunc and RoundEven + give the zero of the source's sign there on either path.""" + x = struct.unpack(" 1 << 24: + return value == source + return value in (round_f64("floor", source), round_f64("ceil", source)) + + +def round_f64_problem(got, out=""): + """Judge a readback of cs_w32_round_f64: "" or the first word that is wrong. `out` is vk_compute_test's output, + for its "device: ..." line. Every result is exact except for the two kinds of source Vulkan leaves to the + driver's double-precision rounding: a NaN may come back as any NaN (a signalling one comes back quiet on the + drivers measured), and a subnormal may be read as a zero of its sign, because the module does not declare + DenormPreserve for 64 bits. On a device in ROUND_F64_FLOAT_PATH the ops named there are held to + round_f64_float_path instead.""" _, expected = round_f64_words() results = [result for thread in round_f64_results() for result in thread] + device = re.search(r"^device: (\S+)", out, re.MULTILINE) + float_path = ROUND_F64_FLOAT_PATH.get(device.group(1), ()) if device else () for index, (op, source) in enumerate(results): value = got[2 * index] | got[2 * index + 1] << 32 want = expected[2 * index] | expected[2 * index + 1] << 32 @@ -544,6 +573,8 @@ def round_f64_problem(got): continue if op is not None and f64_is_subnormal(source) and value == round_f64(op, source & ROUND_F64_SIGN): continue + if op in float_path and round_f64_float_path(op, source, value): + continue what = "the pair an inactive lane keeps" if op is None else f"{op} of {source:#018x}" return f"word {2 * index} (thread {index // 8}): {what} gave {value:#018x}, expected {want:#018x}" for index in range(2 * len(results), len(expected)): @@ -919,8 +950,8 @@ def failure(code, output, lines): def dump_test(tools, spirv, name, want, words, env=None, judge=None): """Run one group with a heap of `words` words and compare the first len(want) words of the whole dump. The - console dump stops at word 7. With `judge`, the whole dump goes to it instead, as a tuple of words, and its - answer ("" for a pass) is returned.""" + console dump stops at word 7. With `judge`, the whole dump goes to it instead, as a tuple of words, with the + test program's output (it names the device), and its answer ("" for a pass) is returned.""" with tempfile.TemporaryDirectory(prefix="leonida-fmt-") as tmp: dump = Path(tmp) / "out.bin" # VKC_OUT_WORDS sets a minimum. Pin this dispatch to exactly `words` words. @@ -937,7 +968,7 @@ def dump_test(tools, spirv, name, want, words, env=None, judge=None): if len(data) != 4 * words: return f"expected {4 * words} dump bytes, got {len(data)}" if judge: - return judge(struct.unpack(f"<{words}I", data)) + return judge(struct.unpack(f"<{words}I", data), out) for i, (expected, got) in enumerate(zip(want, struct.unpack(f"<{words}I", data))): if got != expected: return f"word {i}: expected {expected:#010x}, got {got:#010x}" diff --git a/tests/test_gpu_round_f64.py b/tests/test_gpu_round_f64.py index 52b763ebf7..3ecf966744 100644 --- a/tests/test_gpu_round_f64.py +++ b/tests/test_gpu_round_f64.py @@ -97,11 +97,15 @@ def test_layout(self): self.assertEqual(expected[word(8, 7):word(9, 0)], [0, 0]) +LLVMPIPE = "device: llvmpipe (LLVM 20.1.2, 256 bits) (subgroup 8..8)\n" +NVIDIA = "device: NVIDIA GeForce RTX 4070 Ti (subgroup 32..32)\n" + + class RoundF64Judge(unittest.TestCase): - def judge(self, change): + def judge(self, change, out=""): _, expected = check.round_f64_words() change(expected) - return check.round_f64_problem(tuple(expected)) + return check.round_f64_problem(tuple(expected), out) def set_result(self, thread, slot, bits): def change(data): @@ -142,6 +146,66 @@ def test_everything_else_is_exact(self): self.assertIn(f"word {WORDS - 1}: an input changed", self.judge(lambda data: data.__setitem__(WORDS - 1, 0))) + def test_llvmpipe_s_float_path_passes_for_trunc_and_rndne_and_on_no_other_device(self): + index = check.ROUND_F64_VALUES.index + above_half, big = index(0x3FE0000000000001), index(bits_of(123456789.0625)) + half_tie = index(0x4320000000000001) # 2^51 + 0.5 + # What llvmpipe gave on a CPU without AVX-512: (thread, slot, the word it returned, what the judge calls it). + measured = ((above_half, 2, bits_of(0.0), "rndne of 0x3fe0000000000001"), + (index(bits_of(1.5)), 2, bits_of(1.0), "rndne of 0x3ff8000000000000"), + (index(0xC004000000000001), 2, bits_of(-2.0), "rndne of 0xc004000000000001"), + (index(bits_of(5.5)), 7, bits_of(5.0), "rndne of 0x4016000000000000"), + (big, 0, bits_of(123456789.0625), "trunc of 0x419d6f3454400000"), + (big, 2, bits_of(123456789.0625), "rndne of 0x419d6f3454400000"), + (half_tie, 4, 0xC320000000000001, "trunc of 0xc320000000000001")) # the neg source + for thread, slot, bits, what in measured: + with self.subTest(what=what): + change = self.set_result(thread, slot, bits) + self.assertEqual(self.judge(change, LLVMPIPE), "") + for out in ("", NVIDIA): + self.assertIn(f"word {word(thread, slot)} (thread {thread}): {what}", self.judge(change, out)) + + def test_llvmpipe_s_float_path_is_no_wider_than_measured(self): + index = check.ROUND_F64_VALUES.index + big, tie = index(bits_of(123456789.0625)), index(bits_of(2.5)) + for thread, slot, wrong, what in ( + (tie, 2, bits_of(4.0), "rndne of"), # not a neighbouring integer + (tie, 2, bits_of(-2.0), "rndne of"), # the sign of the source is lost + (tie, 0, bits_of(2.5), "trunc of"), # unchanged, but not above 2^24 + (big, 0, bits_of(123456790.0), "trunc of"), # above 2^24 only the source itself + (index(bits_of(1.5)), 1, bits_of(1.0), "ceil of"), # Ceil is exact on that path + (big, 3, bits_of(123456789.0625), "floor of"), # and so is Floor + (index(0x7FF0000000000000), 2, bits_of(1.0), "rndne of"), # an infinity stays + (2, 2, bits_of(1.0), "rndne of"), # the smallest subnormal: below 0.5 + (index(bits_of(0.25)), 0, bits_of(1.0), "trunc of"), # and so is 0.25 + (9, 7, 0, "the pair an inactive lane keeps")): + with self.subTest(thread=thread, slot=slot, wrong=hex(wrong)): + result = self.judge(self.set_result(thread, slot, wrong), LLVMPIPE) + self.assertIn(f"word {word(thread, slot)} (thread {thread}): {what}", result) + + def test_the_float_path_allowance_covers_the_48_results_measured(self): + """The readback llvmpipe gives without AVX-512, as measured: RoundEven truncates where the binary32 of its + source is a tie or the source is just past one, and Trunc and RoundEven return a magnitude above 2^24 + unchanged. Rebuilt here from those two rules for the inputs they change.""" + _, data = check.round_f64_words() + changed = 0 + truncating = {0x3FE0000000000001, 0xBFE0000000000001, bits_of(1.5), bits_of(-1.5), bits_of(3.5), + bits_of(-3.5), 0xC004000000000001, bits_of(5.5), bits_of(-5.5)} + for thread, results in enumerate(check.round_f64_results()): + for slot, (op, source) in enumerate(results): + value = None + if op in ("trunc", "rndne") and math.isfinite(as_float(source)) and abs(as_float(source)) > 1 << 24: + value = source + elif op == "rndne" and source in truncating: + value = check.round_f64("trunc", source) + if value is not None and value != check.round_f64(op, source): + data[word(thread, slot)], data[word(thread, slot) + 1] = value & 0xFFFFFFFF, value >> 32 + changed += 1 + self.assertEqual(changed, 48) + self.assertEqual(check.round_f64_problem(tuple(data), LLVMPIPE), "") + self.assertIn("word 164 (thread 10): rndne of 0x3fe0000000000001 gave 0x0000000000000000", + check.round_f64_problem(tuple(data))) + class RoundF64Fixture(unittest.TestCase): def test_assembly_stores_the_eight_results_the_oracle_lists(self): @@ -215,6 +279,15 @@ def test_truncated_and_missing_dump_fail(self): self.run_readback(lambda data: data.pop())) self.assertIn("no VKC_DUMP", self.run_readback(missing=True)) + def test_the_device_line_reaches_the_judge(self): + thread = check.ROUND_F64_VALUES.index(bits_of(1.5)) + + def truncated_tie(data): + data[word(thread, 2)], data[word(thread, 2) + 1] = 0, bits_of(1.0) >> 32 + + self.assertEqual(self.run_readback(truncated_tie, output=LLVMPIPE), "") + self.assertIn("rndne of 0x3ff8000000000000", self.run_readback(truncated_tie, output=NVIDIA)) + def test_unsupported_float64_skips_but_nonzero_exit_fails(self): self.assertIsInstance(self.run_readback(code=77, output="unsupported: no Float64\n"), check.Skip) self.assertIn("exit 1", self.run_readback(code=1, output="dispatch failed"))