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 26d010b41dc042bc36698f673ad588a1e6d04f07 Mon Sep 17 00:00:00 2001 From: milk4sale <53350507+milk4sale@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:15:37 -0600 Subject: [PATCH 2/3] rdna2spirv: the binary64 roundings keep a NaN's bits and round a subnormal without the driver (SHADER-ROUND-F64-SPECIALS) v_trunc_f64, v_ceil_f64, v_rndne_f64 and v_floor_f64 hand their source to the driver's double-precision Trunc, Ceil, RoundEven and Floor. Vulkan lets a driver return any NaN for a NaN operand and, with no DenormPreserve for 64 bits, read a subnormal as zero, and cs_w32_round_f64 measured both: a signalling NaN came back quiet on an RTX 4070 Ti (NVIDIA 620.70.06) and on llvmpipe, and llvmpipe read the smallest subnormals as zero, so v_ceil_f64 of the positive one gave +0. RDNA2 returns a NaN unchanged and keeps subnormals: that ceil is 1. The two kinds of source are now selected with integer ops on the words, after the source modifiers and before the output ones. A NaN's words pass through. A subnormal gives a zero of its sign, or 1 with its sign where the op rounds that sign away from zero (ceil of a positive one, floor of a negative one). Every other source still takes the driver's result. cs_w32_round_f64 now compares all 1152 words exactly, on both devices. tests/semantic/test_f64_round.py runs the four ops under a model of a driver that quiets a NaN and reads a subnormal as zero; without the change that class fails for the signalling NaNs and for ceil and floor of a subnormal. The row in docs/design.md describes the rule and how it was confirmed. Co-Authored-By: Claude Fable 5.2 --- docs/design.md | 2 +- docs/testing.md | 28 +++--- runtime/test/shaders/check.py | 26 ++---- runtime/test/shaders/cs_w32_round_f64.asm | 16 ++-- scripts/run_gpu_tests.py | 2 +- tests/semantic/test_f64_round.py | 109 ++++++++++++++++++++++ tests/test_gpu_round_f64.py | 23 ++--- tools/rdna2spirv.py | 45 ++++++++- 8 files changed, 196 insertions(+), 55 deletions(-) diff --git a/docs/design.md b/docs/design.md index d21ee71154..2f8fd52902 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. 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. | +| `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. A NaN and a subnormal are not left to the driver's function: Vulkan lets a driver return any NaN for a NaN operand and, with no `DenormPreserve` for 64 bits, read a subnormal as zero, and both were measured (a signalling NaN came back quiet, sign and payload kept, on an RTX 4070 Ti with NVIDIA 620.70.06 and on llvmpipe; llvmpipe also read the two smallest subnormals as zero, so `v_ceil_f64` of the positive one gave +0 where the hardware gives 1; neither device reports `shaderDenormPreserveFloat64`, and declaring the mode changed nothing on either). The translator selects those two sources with integer ops on the words, after the source modifiers and before the output ones: a NaN's words pass through, and a subnormal gives a zero of its sign, or 1 with its sign where the op rounds that sign away from zero (`v_ceil_f64` of a positive one, `v_floor_f64` of a negative one). GPU-checked 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): all 1152 heap words exact on the RTX 4070 Ti and on llvmpipe (LLVM 23.1.4). CPU-checked under a driver model that quiets a NaN and reads a subnormal as zero by `F64RoundSpecialSources` in `tests/semantic/test_f64_round.py`. | | 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 4d76e9f2e8..b0ae7a1703 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -381,21 +381,25 @@ the largest finite value, the infinities, and quiet and signalling NaNs. Each th `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 +source's sign), and `tests/test_gpu_round_f64.py` checks that oracle against exact rational rounding. All 1152 heap +words are compared exactly, the 128 unchanged input words included: a NaN and a subnormal are rounded by the +translated code with integer ops and not by the driver, as the row in [design.md](design.md) says. 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. +Measured: on an RTX 4070 Ti (NVIDIA 620.70.06, Linux) and on llvmpipe (Mesa 26.2.6, LLVM 23.1.4) all 1152 words +match. While those two kinds of input still went to the driver's function, 15 of the 512 results differed on the +4070 Ti, those of the two signalling NaNs, which came back quiet with sign and payload kept (`0x7ff0000000000001` +gave `0x7ff8000000000001`), and five more on llvmpipe, which read the two smallest subnormals as zero (`v_ceil_f64` +of the positive one gave +0 instead of 1, `v_floor_f64` of the negative one -0 instead of -1). Rules broken one at a +time each failed the test on both devices: a NaN left to the driver (word 784), the NaN and subnormal tests ignoring +the low dword, `v_ceil_f64` or `v_floor_f64` lifting the subnormal of the wrong sign (words 34 and 38), a subnormal's +result losing its sign (word 40), a NaN's low word dropped (word 784), `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 two result words swapped (word 8), and the fixture without its `v_cmpx` (word 30). Two changes are not +caught everywhere: a subnormal left to the driver fails on llvmpipe (word 34) and passes on the 4070 Ti, which keeps +binary64 denormals, and `RoundEven` replaced by GLSL `Round` changes nothing on either device, since both send a tie +to the even integer. ## Wave64 pixel, vertex and geometry shaders (`w64_graphics.py`) diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py index 3c3f45928c..9d4e931cda 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py @@ -485,14 +485,6 @@ def cmp_f64_test(tools, spirv, env=None): 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 @@ -529,23 +521,17 @@ def round_f64_words(): 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.""" + """Judge a readback of cs_w32_round_f64: "" or the first word that is wrong, named by its op and source. Every + word is exact, the results of a NaN and of a subnormal included: the translated code rounds those two itself + and does not leave them to the driver's double-precision functions (docs/design.md).""" _, 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}" + if value != want: + 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}" diff --git a/runtime/test/shaders/cs_w32_round_f64.asm b/runtime/test/shaders/cs_w32_round_f64.asm index 809a793d71..79358129f6 100644 --- a/runtime/test/shaders/cs_w32_round_f64.asm +++ b/runtime/test/shaders/cs_w32_round_f64.asm @@ -17,14 +17,14 @@ ; +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. +; of magnitude 2^52 or more is already integral, an infinity stays, and a NaN and a subnormal are rounded like any +; other value: a NaN comes back unchanged, signalling ones included, 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, except for a NaN and a subnormal, which it rounds with integer ops: Vulkan lets a driver +; return any NaN for a NaN (a signalling one came back quiet on an RTX 4070 Ti and on llvmpipe) and, with no +; DenormPreserve for 64 bits, read a subnormal as zero (llvmpipe did). +; Run with the heap initialized by check.py's round_f64_test; all 1152 words are compared, and the input records +; must come back unchanged. v_lshlrev_b32_e32 v1, 3, v0 v_add_nc_u32_e32 v1, 0x1000, v1 v_lshlrev_b32_e32 v10, 6, v0 diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index aac6efeeed..53c92298a5 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -996,7 +996,7 @@ def run_suite(a, work: str) -> int: 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)")) + detail or "1152 words exact (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/semantic/test_f64_round.py b/tests/semantic/test_f64_round.py index 9d3b50154a..c02c75fe21 100644 --- a/tests/semantic/test_f64_round.py +++ b/tests/semantic/test_f64_round.py @@ -1,4 +1,5 @@ """Value regressions for RDNA2's binary64 round-to-integral instructions.""" +import contextlib import math import shutil import struct @@ -6,8 +7,10 @@ import tempfile import unittest from pathlib import Path +from unittest.mock import patch import support +import spirv_mini_interp def words(value): @@ -31,6 +34,112 @@ def run_op(op, value, *, inactive=False): ]))[:2] +def run_bits(instruction, bits): + """Run one instruction that rounds the pair v[0:1] = `bits` into v[4:5]; return v[4:5] as one 64-bit pattern.""" + low, high = support.mrt0_words(support.translate_lines("ps_f64_case", [ + f"v_mov_b32 v0, {bits & 0xFFFFFFFF:#x}", f"v_mov_b32 v1, {bits >> 32:#x}", + instruction, "exp mrt0 v4, v5, v4, v5 done vm", "s_endpgm", + ]))[:2] + return low | high << 32 + + +@contextlib.contextmanager +def driver_that_quiets_and_flushes(): + """The interpreter's double-precision Trunc, Ceil, RoundEven and Floor, replaced by what Vulkan allows a driver + and what two of them were measured to do (cs_w32_round_f64): a NaN operand comes back with its quiet bit set, + sign and payload kept (NVIDIA 620.70, llvmpipe), and a subnormal operand is read as a zero of its sign + (llvmpipe; the module declares no DenormPreserve for 64 bits). Every other operand is rounded as before. Yields + the list of operands the four functions were called with.""" + calls = [] + + def driver(function): + def rounded(x): + calls.append(x) + if x != x: + bits = struct.unpack(" 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"))