Skip to content

rdna2spirv: widen f16 denormal operands without UnpackHalf2x16 (NVIDIA reads them as 0) - #3220

Merged
ItsNotRexed merged 3 commits into
ItsNotRexed:mainfrom
smowlyy:fix/f16-in-denormal-widen
Nov 23, 2026
Merged

ItsNotRexed merged 3 commits into
ItsNotRexed:mainfrom
smowlyy:fix/f16-in-denormal-widen

Conversation

@smowlyy

@smowlyy smowlyy commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Claimed in the coordination issue: #3047 (comment) (from my finding #2891 (comment)). No item ID yet.

What and why

Gen.f16_in widened every f16 VALU operand to f32 with GLSL.std.450 UnpackHalf2x16. On an RTX 5060 Ti (610.88) that gives 0 for an f16 denormal that an SDWA BYTE_1 select produced. So on main 1628210, ps_sdwa_f16_const fails, natively and under --wave64-emulate:

FAIL  ps_sdwa_f16_const  4096/4096 mismatches; first at (0,0): got ['0xaaaa3800', '0xaaaa0000', '0xaaaa3e00', '0xaaaa73f0'],
                         want ['0xaaaa3800', '0xaaaa1c00', '0xaaaa3e00', '0xaaaa73f0']

It depends on the NVIDIA driver. From the test reports on this PR, main fails this way with 610.88 (RTX 5060 Ti, RTX 3060 Ti, Windows), 595.99.02 (RTX 5090, Linux) and 580.173.02 (RTX 3060 Ti, Linux), and passes with 621.01 (RTX 5080) and 621.24 (RTX 5070, RTX 3080 Laptop). This branch passes on all of them, and on Apple M2 (MoltenVK) and the AMD drivers reported.

Word y is v_mul_f16_sdwa v3, 2.0, v1 src0_sel:BYTE_1 .... BYTE_1 of 2.0 is the f16 denormal 0x0040 (2^-18), and times 1024.0 that's 0x1c00. RDNA2's f16 MODE keeps denormals, and Gen.f16_bits already produces them on the way out. Only the way in lost them.

It isn't every denormal. A local probe (not part of this PR) of 0x0040 × 1024.0 on the same RTX, each word with main's translator and this branch's:

source of the denormal main this branch
v_mul_f16_sdwa, inline constant 2.0, src0_sel:BYTE_1 0x0000 0x1c00
v_mul_f16_sdwa, 0x4000 in a VGPR, src0_sel:BYTE_1 0x0000 0x1c00
v_mul_f16_e32, literal 0x40 0x1c00 0x1c00
v_mul_f16_e32, 0x40 in a VGPR 0x1c00 0x1c00

v_add_f16, v_fma_mixlo_f16, v_pk_mul/add/fma_f16 and v_cvt_f32_f16 with a denormal in a VGPR also gave the right words on main. Why the SDWA-selected value is different I don't know: both reach UnpackHalf2x16 with 0x0040 in the low 16 bits. The fix doesn't depend on that: it doesn't use UnpackHalf2x16 for exponent-0 halves at all.

  • tools/rdna2spirv.py Gen.f16_in: when the half's exponent field is 0, the operand is sign × mantissa × 2^-24 (OpConvertUToF of the 10-bit mantissa, exact in f32). Other halves keep the UnpackHalf2x16 result, so normal, inf and NaN halves are unchanged.
  • tests/semantic/test_value_semantics.py: test_f16_denormal_operand_does_not_rely_on_unpack_half runs ps_sdwa_f16_const through the interpreter with an UnpackHalf2x16 that flushes denormals, as NVIDIA's does. It needs the same four words as the existing test.
  • docs/design.md: the "f16 rounding" row adds the widening side, with how it was confirmed.

Not changed: the other UnpackHalf2x16 uses (packed-f16 reads, interpolants, d16 image results). They may read denormals the same way, but no test here shows it, so I left them alone.

Tested

AI-assisted (Claude Code). AMD Ryzen 5 7600X, Windows 11 Home 26300. GPUs: NVIDIA GeForce RTX 5060 Ti, driver 610.88 (subgroup 32..32); AMD Radeon(TM) Graphics iGPU (RDNA2 gfx1036, subgroup 32..64), driver 24.10.24 (Vulkan driver 2.0.302). MSVC 14.44, Vulkan SDK 1.4.363.0, llvm-mc 21.1.8 (scripts\build_llvm_mc.ps1), Python 3.12.10. Test programs built with scripts\build_runtime.ps1. Implicit layers off. No game files.

python -I scripts/run_gpu_tests.py, whole suite:

device mode main 1628210 this branch
RTX 5060 Ti native 142/189, 1 failed (ps_sdwa_f16_const) 143/189, 0 failed; ps_sdwa_f16_const 4096/4096 exact
RTX 5060 Ti LEONIDA_W64_EMULATE=1 173/189, 1 failed (ps_sdwa_f16_const) 174/189, 0 failed; ps_sdwa_f16_const 4096/4096 exact
Radeon iGPU native 91/189, 0 failed 91/189, 0 failed
Radeon iGPU LEONIDA_W64_EMULATE=1 91/189, 0 failed 91/189, 0 failed

The iGPU skips ps_sdwa_f16_const and most pixel tests (128-byte push constants), so the change only has an NVIDIA GPU result here. A desktop RDNA2 run would help.

  • python -m unittest discover -s tests/semantic: 4143 tests OK (main: 4142). The new test fails on main's translator with '0xaaaa0000' != '0xaaaa1c00' (component y) and passes with the change.
  • python -I tests/semantic/regen_fixtures.py --check: exit 0.
  • python -I tests/test_shader_checks.py, python -I tests/test_docs_design_rows.py: OK.
  • python -m compileall -q make_game.py tools tests: clean.
  • Not run: tests/test_translate.py (needs pytest, not installed here).

Checklist

  • No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here.
  • A new translator rule is in the contract table of docs/design.md, with how it was confirmed.

🤖 Generated with Claude Code

Gen.f16_in widened every f16 VALU operand with GLSL.std.450
UnpackHalf2x16. NVIDIA's reads an f16 denormal as 0 (RTX 5060 Ti,
610.88), so ps_sdwa_f16_const's word y, the denormal 0x0040 times
1024.0, came back 0x0000 instead of 0x1c00 natively and under
--wave64-emulate. RDNA2's f16 MODE keeps denormals.

A half with a zero exponent field is now widened exactly as
sign * mantissa * 2^-24 with integer ops; other halves keep the
UnpackHalf2x16 result. A semantic test runs ps_sdwa_f16_const with a
flushing UnpackHalf2x16 and fails on the old translation.

AI-assisted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A local probe on the RTX 5060 Ti (610.88) found that UnpackHalf2x16
loses an f16 denormal only when an SDWA BYTE_1 select produced it,
from an inline constant or a VGPR alike; the same denormal as a
literal or already in a VGPR widens right on main. The code is
unchanged; the docstring, the test comment and the design.md row now
say that instead of "NVIDIA reads denormals as 0".

AI-assisted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@maxhurst131

Copy link
Copy Markdown
Contributor

Independent check, AI-assisted.

Tested 3b99b37 on Windows 11 build 26300 (MSVC, Vulkan SDK 1.4.363.0):

  • NVIDIA GeForce RTX 5070, driver 32.0.16.2124 (subgroup 32..32): ps_sdwa_f16_const passes 4096/4096 pixels with python -I scripts/run_gpu_tests.py --build <runtime> --llvm-mc "wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc" --filter ps_sdwa_f16_const --require-pass, LEONIDA_VK_DEVICE=NVIDIA.
  • AMD Radeon(TM) Graphics (gfx1036, Ryzen 5 7600X), driver 32.0.21045.29003 (subgroup 32..64): passes 4096/4096, same command with LEONIDA_VK_DEVICE=AMD Radeon.

Caveat: the same fixture also passes at base 1628210 on both GPUs and drivers (same build folder, same command, filter set to each adapter), so the UnpackHalf2x16 denormal flush described in the PR does not reproduce on these two configurations. The new semantic test still passes here (test_f16_denormal_operand_does_not_rely_on_unpack_half, 34/34 in tests/semantic/test_value_semantics.py with the flushing UnpackHalf2x16), so the change is covered; only the hardware failure looks driver-specific.

No game files used; counts only.

@tylerstraub

Copy link
Copy Markdown
Contributor

Tested 3b99b37ee8905a3c7240cf390f6f0c63ba093f03 on NVIDIA GeForce RTX 5090, 595.99.02 (Linux).

Independent Linux Vulkan check of 3b99b37e on an RTX 5090 (595.99.02, subgroup 32). The stock ps_sdwa_f16_const fixture returned aaaa3800 aaaa1c00 aaaa3e00 aaaa73f0 at all 4,096 pixels with LEONIDA_W64_EMULATE set to 0 and to 1. Reverting only the translator change gave aaaa0000 in the second word at every pixel under both settings. The other three words matched throughout.

All four generated modules passed SPIR-V validation for Vulkan 1.2. Disassembly confirmed that none declared DenormPreserve 16, so this result isolates the operand-widening fix. The focused CPU regression also passed. GPU coverage here is limited to this synthetic fixture on this driver. AI-assisted.

AI-assisted verification.

@lines9686-rgb

Copy link
Copy Markdown

Tested 3b99b37 on NVIDIA GeForce RTX 3060 Ti (Ampere), driver 610.88, Vulkan 1.4.341, Windows 11 (26200): pass, and the bug reproduces on main.

Test programs built from this commit (MSVC from VS 2026 + Ninja); llvm-mc 23.1.6 (conda-forge llvm-tools); SPIRV-Tools from Vulkan SDK 1.4.357.0. Same harness, only tools/rdna2spirv.py swapped:

ps_sdwa_f16_const native LEONIDA_W64_EMULATE=1
translator from main (1628210) FAIL, 4096/4096: got 0xaaaa0000 for word y, want 0xaaaa1c00 FAIL, same words
this PR PASS, 4096/4096 exact PASS, 4096/4096 exact
  • run_gpu_tests.py --filter f16 on this PR: 16 translated, 16 pass spirv-val, 15/15 PASS.
  • tests/semantic/test_value_semantics.py: OK.

So the flushed f16 denormal on the SDWA path is not Blackwell-only: Ampere reads it as 0 as well on this driver. No game files. AI-assisted (Claude Code).

@sds-228

sds-228 commented Nov 22, 2026

Copy link
Copy Markdown
Contributor

Tested 3b99b37e on NVIDIA RTX 3080 Laptop (Ampere), driver 621.24, Vulkan 1.4.357, Windows 11: pass, no regression.

  • Focused run_gpu_tests.py --filter ps_sdwa_f16_const: 1/1, 4096/4096 pixels exact; 1 shader translated, 1 passed spirv-val.
  • Full scripts/run_gpu_tests.py: 143/189 passed, 46 skipped, 0 failed — same as the main baseline (6d119bd5) on this card.
  • llvm-mc 21.1.8, Windows SPIRV-Tools via WSL forwarders; CPU-only translator changes (no runtime rebuild). Synthetic tests only, no game files.

Note: this driver passes ps_sdwa_f16_const on main too (no DenormPreserve 16 in the module, yet no flush here), so this run confirms no regression rather than independently proving the NVIDIA fix on the 610.88/5060 Ti setup. AI-assisted (OpenCode).

@bobcatchris

Copy link
Copy Markdown
Contributor

Apple M2 no-regression check. Tested head 3b99b37 on Apple M2 (Mac14,3), macOS 26.4 (25E246), MoltenVK 1.4.2 (direct), subgroup 4..32, llvm-mc 23.1.6, Python 3.13.18.

python -I scripts/run_gpu_tests.py --build runtime/build/linux: 193 shaders translated, 193 pass spirv-val; 116/189 passed, 72 skipped, 1 failed — identical to current main 1628210 on this M2 (the failure is the separately tracked ps_ssharp S# LOD-bias case, fixed by open #1845). ps_sdwa_f16_const passes on this driver both before and after the change, so this is an Apple/MoltenVK no-regression data point; it does not test the NVIDIA denormal-flush case the PR targets.

Build note: full build fails on AppleClang 17 at vk_pipeline_check.cpp:567 (BUILD-822, fixed by open PR #2927); GPU binaries built, so the suite above is valid. Head fetched read-only; no rebase/edit/push. Synthetic shaders and counts only; no game files.

AI-assisted.

@TreXito

TreXito commented Nov 22, 2026

Copy link
Copy Markdown
Contributor

Tested 3b99b37e on NVIDIA GeForce RTX 3060 Ti (Ampere, subgroup 32..32), driver 580.173.02 (Vulkan 1.4.312), Linux (Ubuntu 26.04 container on a TrueNAS 26.0 host): pass, it fixes ps_sdwa_f16_const here.

python3 -I scripts/run_gpu_tests.py, whole suite, fresh --work, Linux runtime built from the branch (CMake + Ninja, GCC, RelWithDebInfo):

main 1628210 this branch
native 142/189 passed, 46 skipped, 1 failed: ps_sdwa_f16_const, lane y 0xaaaa0000 (want 0xaaaa1c00) 143/189 passed, 46 skipped, 0 failed
  • ps_sdwa_f16_const is the only test whose result changes: 4096/4096 pixels exact.
  • build.py: 194 shaders, 194 translated, 194 pass spirv-val.
  • This driver reports shaderDenormPreserveFloat16 = true, shaderDenormFlushToZeroFloat16 = false, denormBehaviorIndependence = ALL, and still flushes the SDWA-selected denormal on main. So this is an Ampere card on the Linux 580 branch, which the Windows 610/621 reports above don't cover.
  • Tools: llvm-mc 21.1.8, SPIRV-Tools 2026.1, glslang 16.2.0, CMake 4.2.3, Python 3.14.4.

AI-assisted (Claude Code). Synthetic test shaders only, no game files.

@TheMrBeez

Copy link
Copy Markdown

Tested 3b99b37e (base 16282101) on a second Blackwell card. Pass, and one data point on the failure itself: it doesn't reproduce on RTX 5080 / NVIDIA 621.01. AI-assisted run, synthetic shaders only, no game files.

scripts/run_gpu_tests.py --filter ps_sdwa_f16_const, Windows 11 Pro 10.0.26200, llvm-mc from rocm-sdk-core 10.0.0, test programs built at the base:

translator RTX 5080 (621.01), native RTX 5080, LEONIDA_W64_EMULATE=1 gfx1036 iGPU (AMD 25.10.30.02)
base 16282101 4096/4096 exact 4096/4096 exact 4096/4096 exact
this PR 4096/4096 exact 4096/4096 exact 4096/4096 exact

So on 621.01 (an RTX 5080), UnpackHalf2x16 of the SDWA-selected 0x0040 keeps the denormal, unlike your RTX 5060 Ti on 610.88. The NVIDIA behaviour depends on the driver or the card. The PR doesn't depend on that either way, since it no longer uses UnpackHalf2x16 for exponent-0 halves, and that's the safer choice given the difference.

Also:

  • python -m unittest discover -s tests/semantic -p test_value_semantics.py: 34 tests OK (33 at the base). With tools/rdna2spirv.py reverted to the base, the new test_f16_denormal_operand_does_not_rely_on_unpack_half fails (component y), so the test catches the old path.
  • Full run_gpu_tests.py with this translator: RTX 5080 143/189 (46 skipped, wave64), iGPU 174/189 (15 skipped), no failures.

Testers on ItsNotRexed#3220 saw ps_sdwa_f16_const fail on main with NVIDIA
610.88, 595.99 and 580.173, and pass with 621.01 and 621.24. The row
now says so; the translation is unchanged.

AI-assisted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@JRamos1993

Copy link
Copy Markdown
Contributor

Tested 9d71037 on an RTX 5090 (driver 616.92), Windows 11, Vulkan SDK 1.4.363. The GPU test programs were built from the same tree:

  • scripts/run_gpu_tests.py: 143/189 passed, 46 skipped, 0 failed. main 1628210 gives 143/189, 46 skipped, 0 failed. All 194 test shaders translate and pass spirv-val.
  • tests/semantic/test_value_semantics.py: ran 34 tests in 2.224s; OK.

AI-assisted (Claude Code).

@TreXito

TreXito commented Nov 22, 2026

Copy link
Copy Markdown
Contributor

Follow-up on the same RTX 3060 Ti (580.173.02, Linux), now at d6bb62ec. Since 3b99b37e only docs/design.md changed. This run is the whole suite with LEONIDA_W64_EMULATE=1, which runs the 31 wave64 tests the native run skips:

base 16282101 d6bb62ec
LEONIDA_W64_EMULATE=1 173/189 passed, 15 skipped, 1 failed (ps_sdwa_f16_const) 174/189 passed, 15 skipped, 0 failed

ps_sdwa_f16_const is again the only test whose result changes (4096/4096 exact). The 15 skips are the same on both: the D3D12-run cases and ps_w64x_readlane. AI-assisted (Claude Code), synthetic test shaders only.

@FIocker

FIocker commented Nov 22, 2026

Copy link
Copy Markdown
Contributor

Independent Windows GPU check, run with Codex assistance. I tested 3b99b37ee8905a3c7240cf390f6f0c63ba093f03 against base 162821017ea3c286c8bec860f3ff94f037912061 on a desktop RTX 5080, NVIDIA 621.01, Vulkan 1.4.357, subgroup 32..32, Windows 11 Pro build 26200. The harnesses were built with MSVC 19.44. The repository’s scripts/run_gpu_tests.py used LLVM 23.1.6 and SPIRV-Tools 2026.4.

Mode Base PR
Native 143 passed, 46 skipped 143 passed, 46 skipped
LEONIDA_W64_EMULATE=1 174 passed, 15 skipped 174 passed, 15 skipped

All 194 shader modules translated and passed spirv-val in each run. All 189 individual test outcomes matched between revisions in each mode. ps_sdwa_f16_const matched all 4,096 pixels on both revisions in both modes, so the reported GPU failure did not reproduce on this setup.

With the regression test’s simulated denormal flushing, the base produced 0xaaaa0000 for component Y and the PR produced 0xaaaa1c00. All 34 tests in test_value_semantics.py passed on the PR. All inputs were synthetic.

@lines9686-rgb

Copy link
Copy Markdown

A note next to @FIocker's run: the base fails ps_sdwa_f16_const on my RTX 3060 Ti with driver 610.88 (word y 0xaaaa0000, same as the description), while it passes on the RTX 5080 with 621.01. So the flushed f16 denormal on the SDWA path looks driver-dependent (610.88 has it, 621.01 doesn't), and the fix still matters for players on older drivers. AI-assisted (Claude Code).

@zzEmmazz

zzEmmazz commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Rebase check for the A/B that @bobcatchris asked about in the coordination issue: d6bb62ec on current main f847748c, and what it does there.
Windows 11 (26200), MSVC 14.50 (VS 2026), Ninja RelWithDebInfo, llvm-mc 21.1.8, Vulkan SDK 1.4.363. Two GPUs: Ryzen 7 9700X iGPU (RDNA2, AMD 32.0.21042.62) and RTX 3070 (Ampere, NVIDIA 610.74), picked with LEONIDA_VK_DEVICE.

The conflict is in one row of docs/design.md only. tools/rdna2spirv.py and tests/semantic/test_value_semantics.py apply cleanly on f847748c (git apply --3way). In the "f16 rounding (SHADER-55, SHADER-56)" row, main has since changed the sentence after "…the 16-bit interpolant quantize (#512) are separate." (it now reads "v_fma_mix* with f32 sources rounds once…"), which is where this PR inserts its "Widening an f16 ALU operand doesn't trust UnpackHalf2x16 with denormals" passage. Keeping main's row and inserting the PR's passage at the same place resolves it; tests/test_docs_design_rows.py and tests/test_docs_links.py pass on the result.

With that applied on f847748c (whole scripts/run_gpu_tests.py, test programs built from f847748c, 204 of 204 shaders translate and pass spirv-val on both trees):

GPU main f847748c f847748c + this PR
RTX 3070 (610.74) 152/199 passed, 46 skipped, 1 failed: ps_sdwa_f16_const (word y 0xaaaa0000, want 0xaaaa1c00) 153/199 passed, 46 skipped, 0 failed
Radeon iGPU 184/199 passed, 15 skipped, 0 failed 184/199 passed, 15 skipped, 0 failed

Test by test, the only result that changes on either GPU is ps_sdwa_f16_const on the RTX 3070, from FAIL to PASS. So the failure also reproduces on an RTX 3070 with 610.74, and the fix holds on current main. python -m unittest discover -s tests/semantic -p test_value_semantics.py: 35 tests OK.

Not checked: MoltenVK (no Mac here), the complete tests/semantic suite, and --wave64-emulate runs.

The diff against f847748c (for git apply)
diff --git a/docs/design.md b/docs/design.md
index 40e42950..1a8678ec 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -365,7 +365,7 @@ How the generated SPIR-V expects the runtime to work:
 | `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` 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) give the translator's word, the kept destination half included, except one: with all three operands NaN the hardware returns src0's NaN bits unchanged (`0x7c01` stays a signalling NaN under IEEE 0), the translator a quiet NaN, as for the 32-bit ops (*Float min/max/med3 with NaN*). `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`. |
 | `v_cvt_pknorm_i16_f32`, `v_cvt_pknorm_u16_f32` | D[15:0] from S0 and D[31:16] from S1: the f32 is clamped to [-1, 1] (i16) or [0, 1] (u16), multiplied by 32767 or 65535 and rounded to nearest even **once, from the exact product** (SHADER-363). Mesa ACO emits these opcodes for NIR `pack_snorm_2x16`/`pack_unorm_2x16`, which `nir_opcodes.py` defines as `fround_even(fclamp(x) * 32767.0 / 65535.0)`. Emitted as `FClamp`, `OpFMul`, `RoundEven` and a convert, not `PackSnorm2x16`, whose rounding GLSL leaves to the driver. The f32 `OpFMul` can land exactly on k + 0.5 when the exact product is just below or above it, and `RoundEven` would then pick the even neighbour; the product's error `Fma(c, s, -p)` is exact, so on such a tie the translator takes floor(p) + 1 when it is positive, floor(p) when negative, and `RoundEven` when it is 0 (an exact tie). Away from a tie the two roundings agree, since k + 0.5 is an f32 there. NaN gives 0, as `v_cvt_i32_f32` does: **measured** on an RDNA2 iGPU (gfx1036, SHADER-339), 74 of 74 NaN halves (quiet and signalling, both signs, payloads, in S0 and S1) gave 0 in wave32 and wave64 under the game's MODE and with IEEE 1, DX10_CLAMP 0 or f32 denormals kept (`tools/pknorm_probe.py --oracle hw`). **The rounding differs:** the hardware rounds the exact product x · 32767 (or 65535) once, while the translator rounds the f32 `OpFMul` product and then `RoundEven`, so it is one off where the f32 product lands exactly on k + 0.5 (28 of 28 such near-tie inputs, both directions; `docs/shader_validation.md`, "`v_cvt_pknorm_*` NaN and rounding on RDNA2"). On gfx1035 (SHADER-137, `tools/int_hw_probe.py --oracle both`, wave32 and wave64) ±qNaN → 0, ±inf saturation and the round-to-nearest-even ties at ±0.5 match bit for bit. Not fixed here. NaN gives 0, as `v_cvt_i32_f32` does; that is **not measured on hardware**. Source modifiers apply. `clamp` raises `Unsupported`. Until 2026-11-22 both ops were rejected. **Measured on RDNA2:** on an iGPU (gfx1036, SHADER-339/363, `tools/pknorm_probe.py --oracle hw`) 74 of 74 NaN halves (quiet and signalling, both signs, payloads, in S0 and S1) gave 0 and 28 of 28 near-tie inputs (both directions) gave the single-rounded word, in wave32 and wave64 under the game's MODE and with IEEE 1, DX10_CLAMP 0 or f32 denormals kept; the translator matches all 134 probe words in all ten runs (it was one off on the 28 near ties before SHADER-363; CPU-checked by `tests/semantic/test_alu_cvt_pknorm_f32.py` (the twelve measured near-tie words, ties at the scale steps, ±inf, ±NaN, subnormals, out-of-range values, 40 seeded pairs, abs/neg) and `tests/test_pknorm_probe.py`. **Not checked through Vulkan on a GPU.** **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137): ±qNaN → 0, ±inf saturation, and round-to-nearest-even ties at ±0.5 match bit-for-bit (the near-tie rounding above is a separate case). **Not GPU-verified.** |
-| f16 rounding (SHADER-55, SHADER-56) | **Narrowing to f16 uses integer ops, not `PackHalf2x16`.** Every f16 ALU result (`v_*_f16` VOP1/VOP2/VOP3, `v_pk_*_f16`, `v_cvt_f16_f32`, `v_interp_p2_f16`, `v_fma_mix*`) and `v_cvt_pkrtz_f16_f32` go through `Gen.f16_bits` (round to nearest even, or round toward zero for pkrtz; f16 denormals kept, f32 denormal inputs give ±0, NaN stays a quiet NaN). After a MODE.FP_ROUND toward-zero write the ALU results take the toward-zero form instead (`Gen.f16_res`; see Known approximations). GLSL.std.450 leaves `PackHalf2x16`'s rounding to the implementation, and drivers fold a `PackHalf2x16` → `UnpackHalf2x16` round trip to a no-op, so the next f16 op saw the unrounded f32: #513 (RTX 6000 Ada, `--wave64-emulate`, `v_pk_add_f16` → `v_pk_mul_f16` 1 ulp off), and pkrtz giving round-to-nearest on llvmpipe. **f16 FMAs round once** (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`): x·y is exact in f32, TwoSum gives the exact error of the f32 sum, and round-to-odd at f32 then rounds correctly to f16. An RX 6700 matched a correctly rounded f16 FMA in 12,612 of 12,612 cases (#374); `Fma` then narrowing double-rounded. Checked by `tests/semantic/test_f16_int_convert.py` (edges + seeded sweep against Python's binary16), `tests/semantic/test_f16_fma_rounding.py` (exact rational reference; built near-tie cases fail on the old translation) and `tools/valu_fuzz.py --family f16` on an RTX 6000 Ada. Image/buffer d16 packing (#489) and the 16-bit interpolant quantize (#512) are separate. `v_fma_mix*` with f32 sources rounds once straight to f16 via round-to-odd in both nearest and toward-zero modes (measured on an RDNA2 iGPU, gfx1036: `tools/fma_mix_probe.py --oracle hw` gave the single-rounded word for all 7 of 7 tie inputs where the two rules differ, SHADER-135; see Known approximations). `v_fma_mix*` rounds once straight to f16 via round-to-odd in both nearest-even and toward-zero modes, matching hardware (7 of 7 tie inputs of `tools/fma_mix_probe.py --oracle hw` on gfx1036, SHADER-135; see Known approximations). `v_fma_mix*` rounds once straight to f16 via round-to-odd in both nearest and toward-zero modes (see Known approximations); the hardware rounds once: 7 of 7 tie inputs of `tools/fma_mix_probe.py --oracle hw` on gfx1036 (SHADER-135). `v_fma_mix*` with f32 sources uses `Fma` then narrows (two roundings, unmeasured) in nearest-even mode; toward zero it rounds once (see Known approximations). 7 of 7 tie inputs of `tools/fma_mix_probe.py --oracle hw` on gfx1036 (SHADER-135; not fixed yet); toward zero it rounds once (see Known approximations). |
+| f16 rounding (SHADER-55, SHADER-56) | **Narrowing to f16 uses integer ops, not `PackHalf2x16`.** Every f16 ALU result (`v_*_f16` VOP1/VOP2/VOP3, `v_pk_*_f16`, `v_cvt_f16_f32`, `v_interp_p2_f16`, `v_fma_mix*`) and `v_cvt_pkrtz_f16_f32` go through `Gen.f16_bits` (round to nearest even, or round toward zero for pkrtz; f16 denormals kept, f32 denormal inputs give ±0, NaN stays a quiet NaN). After a MODE.FP_ROUND toward-zero write the ALU results take the toward-zero form instead (`Gen.f16_res`; see Known approximations). GLSL.std.450 leaves `PackHalf2x16`'s rounding to the implementation, and drivers fold a `PackHalf2x16` → `UnpackHalf2x16` round trip to a no-op, so the next f16 op saw the unrounded f32: #513 (RTX 6000 Ada, `--wave64-emulate`, `v_pk_add_f16` → `v_pk_mul_f16` 1 ulp off), and pkrtz giving round-to-nearest on llvmpipe. **f16 FMAs round once** (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`): x·y is exact in f32, TwoSum gives the exact error of the f32 sum, and round-to-odd at f32 then rounds correctly to f16. An RX 6700 matched a correctly rounded f16 FMA in 12,612 of 12,612 cases (#374); `Fma` then narrowing double-rounded. Checked by `tests/semantic/test_f16_int_convert.py` (edges + seeded sweep against Python's binary16), `tests/semantic/test_f16_fma_rounding.py` (exact rational reference; built near-tie cases fail on the old translation) and `tools/valu_fuzz.py --family f16` on an RTX 6000 Ada. Image/buffer d16 packing (#489) and the 16-bit interpolant quantize (#512) are separate. **Widening an f16 ALU operand doesn't trust `UnpackHalf2x16` with denormals** (`Gen.f16_in`): on an RTX 5060 Ti (610.88) it gives 0 for a denormal that an SDWA `BYTE_1` select produced, from an inline constant or a VGPR alike, while the same denormal as a literal or already in a VGPR widens right (a local probe of all four, before and after). It depends on the driver: `ps_sdwa_f16_const` failed this way on `main` with NVIDIA 610.88 (RTX 5060 Ti, RTX 3060 Ti, Windows), 595.99 (RTX 5090, Linux) and 580.173 (RTX 3060 Ti, Linux), and passed with 621.01 (RTX 5080) and 621.24 (RTX 5070, RTX 3080 Laptop) (#3220). So a half whose exponent field is 0 is widened as sign × mantissa × 2^-24 with integer ops. Confirmed by the GPU test `ps_sdwa_f16_const` (word y, the denormal `0x0040` × 1024.0 = `0x1c00`), which gave `0x0000` on an RTX 5060 Ti (610.88) natively and under `--wave64-emulate` before and 4096/4096 exact after, and by `tests/semantic/test_value_semantics.py` running it with a flushing `UnpackHalf2x16`. The other `UnpackHalf2x16` uses (packed-f16 reads, interpolants, d16 image results) are not changed. `v_fma_mix*` with f32 sources rounds once straight to f16 via round-to-odd in both nearest and toward-zero modes (measured on an RDNA2 iGPU, gfx1036: `tools/fma_mix_probe.py --oracle hw` gave the single-rounded word for all 7 of 7 tie inputs where the two rules differ, SHADER-135; see Known approximations). `v_fma_mix*` rounds once straight to f16 via round-to-odd in both nearest-even and toward-zero modes, matching hardware (7 of 7 tie inputs of `tools/fma_mix_probe.py --oracle hw` on gfx1036, SHADER-135; see Known approximations). `v_fma_mix*` rounds once straight to f16 via round-to-odd in both nearest and toward-zero modes (see Known approximations); the hardware rounds once: 7 of 7 tie inputs of `tools/fma_mix_probe.py --oracle hw` on gfx1036 (SHADER-135). `v_fma_mix*` with f32 sources uses `Fma` then narrows (two roundings, unmeasured) in nearest-even mode; toward zero it rounds once (see Known approximations). 7 of 7 tie inputs of `tools/fma_mix_probe.py --oracle hw` on gfx1036 (SHADER-135; not fixed yet); toward zero it rounds once (see Known approximations). |
 | `s_round_mode` | SIMM16[3:0] sets FP_ROUND. The translator accepts FP32 nearest-even with FP16/64 nearest-even or toward-zero and writes the same per-invocation state as `s_setreg_imm32_b32`. Other rounding modes raise Unsupported. AMD RDNA2 ISA tables 15 and 24; synthetic positive and negative halfway-neighbour conversions in `test_scalar_noop_waitcnt.py` check both modes in one shader. |
 | f16 narrowing size | `Gen.f16_bits` leaves out two steps that can't change the result. In nearest-even mode there is no separate infinity select: infinity is already at or above the overflow threshold (65520), which gives 0x7C00. For `v_add_f16`, `v_sub_f16`, `v_subrev_f16` and `v_pk_add_f16` without omod (`exact_tiny`), the range below 2^-14 is neither rounded nor tested for underflow: a sum of two f16 values is a multiple of 2^-24, so there it is already an f16 value, and clamp keeps that true. With an omod the rounding stays, since `div:2` can create a tie. Confirmed by running the emitted integer sequences before and after on all 2^32 f32 inputs (both roundings) and on all 2^32 f16 operand pairs (both roundings, with and without clamp): no difference. Regression test: `tests/semantic/test_f16_sum_narrowing.py`. |
 | `v_interp_p2_f16` clamp | The VOP3 `clamp` bit on `v_interp_p2_f16` clamps its f16 result to [0, 1], applied before the narrowing like the other f16 results (Mesa ACO `aco_opcodes.py` declares the op `dst(F16)`, which takes output modifiers; llvm-mc encodes `clamp` on it but no omod). Until 2026-11-22 the translator dropped it. Checked by `tests/semantic/test_interp_f16.py`: attributes 1.5 and -0.25 read with clamp give 1.0 and +0.0, and without it 1.5 and -0.25. No GPU test: `vs_ids` gives attributes in [0, 1) only. |
diff --git a/tests/semantic/test_value_semantics.py b/tests/semantic/test_value_semantics.py
index 99ffc117..7f80e7a7 100644
--- a/tests/semantic/test_value_semantics.py
+++ b/tests/semantic/test_value_semantics.py
@@ -58,6 +58,7 @@ import os
 import struct
 import sys
 import unittest
+from unittest import mock
 
 import support
 import spirv_mini_interp as si
@@ -469,6 +470,17 @@ class TranslatorValueSemantics(unittest.TestCase):
         # 0x0040; an SGPR source and v_cvt_f16_u16 reading the f32 bits of 1.0 are narrowed the same way.
         self.check("ps_sdwa_f16_const", EXPECTED_SDWA_F16_CONST)
 
+    def test_f16_denormal_operand_does_not_rely_on_unpack_half(self):
+        # On NVIDIA (RTX 5060 Ti, 610.88) UnpackHalf2x16 gives 0 for the denormal 0x0040 that word y's BYTE_1
+        # select produces. Here every denormal is flushed, so y stays 0x1c00 only if they skip UnpackHalf2x16.
+        real = si.half_to_float
+
+        def flushing(h):
+            return math.copysign(0.0, -1.0 if h & 0x8000 else 1.0) if (h & 0x7C00) == 0 else real(h)
+
+        with mock.patch.object(si, "half_to_float", flushing):
+            self.check("ps_sdwa_f16_const", EXPECTED_SDWA_F16_CONST)
+
     def test_s_buffer_load_dwordx2_into_vcc(self):
         # The V# in s[0:3] points at 0x1000; the two dwords must come back in vcc_lo and vcc_hi, not be lost.
         push = [0x1000, 0, 16, 0] + [0] * 28
diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py
index 87c3175c..5b36749f 100644
--- a/tools/rdna2spirv.py
+++ b/tools/rdna2spirv.py
@@ -534,12 +534,31 @@ class Gen:
         return out
 
     def f16_in(self, s, hi=0):
-        """Read operand ``s`` as an f16 (low half, or high half when ``hi``) widened to f32, then apply its neg/abs."""
+        """Read operand ``s`` as an f16 (low half, or high half when ``hi``) widened to f32, then apply its neg/abs.
+
+        RDNA2's f16 MODE keeps denormals, but on NVIDIA (RTX 5060 Ti, 610.88) UnpackHalf2x16 gives 0 for a denormal
+        that an SDWA BYTE_1 select produced, from an inline constant or a VGPR alike (ps_sdwa_f16_const), while the
+        same denormal in a register or a literal widens right. A half with a zero exponent field is therefore
+        widened exactly with integer ops: sign * mantissa * 2^-24."""
         u = self.src_h(s)
         v2, f = self.tmp(), self.tmp()
         self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {u}")
         self.emit(f"{f} = OpCompositeExtract %float {v2} {1 if hi else 0}")
-        return self.modify_f(f, s)
+        h, ex, small, mant, mf, den, neg, isneg, sden, out = (self.tmp() for _ in range(10))
+        if hi:
+            self.emit(f"{h} = OpShiftRightLogical %uint {u} {self.cu(16)}")
+        else:
+            self.emit(f"{h} = OpBitwiseAnd %uint {u} {self.cu(0xFFFF)}")
+        self.emit(f"{ex} = OpBitwiseAnd %uint {h} {self.cu(0x7C00)}")
+        self.emit(f"{small} = OpIEqual %bool {ex} {self.cu(0)}")
+        self.emit(f"{mant} = OpBitwiseAnd %uint {h} {self.cu(0x3FF)}")
+        self.emit(f"{mf} = OpConvertUToF %float {mant}")
+        self.emit(f"{den} = OpFMul %float {mf} {self.fconst(2.0 ** -24)}")
+        self.emit(f"{neg} = OpFNegate %float {den}")
+        self.emit(f"{isneg} = OpUGreaterThanEqual %bool {h} {self.cu(0x8000)}")
+        self.emit(f"{sden} = OpSelect %float {isneg} {neg} {den}")
+        self.emit(f"{out} = OpSelect %float {small} {sden} {f}")
+        return self.modify_f(out, s)
 
     def fma_mix_srcs(self, a, mods):
         """Read the 3 operands of v_fma_mix*: f16 at op_sel[i] when op_sel_hi[i] is set (via src_h so fimm is binary16), else f32."""

dev-ewann pushed a commit to dev-ewann/Leonida that referenced this pull request Nov 22, 2026
# Conflicts:
#	docs/design.md
@Mohamed-Leo

Copy link
Copy Markdown
Contributor

Independent Windows Vulkan check on an NVIDIA GeForce RTX 5060 Ti (NVIDIA 621.14, Vulkan 1.4.357, subgroup 32..32). The reported ps_sdwa_f16_const failure does not reproduce on this driver.

I translated the repository's synthetic fixture on main aa2988cc, then repeated the same test with only Gen.f16_in replaced by its implementation immediately before 9d71037c. The same upstream CI-built vk_harness (4eb6155d) and fullscreen vertex shader were used for both. Both implementations were bit-exact at all 4,096/4,096 pixels, with and without the translator's wave64 emulation flag.

A separate focused run on aa2988cc passed 17/17 pixel fixtures in each configuration, including SDWA, packed f16, comparisons and NaN cases. This was a subset of the synthetic GPU fixtures. No game data was used. AI-assisted with Codex.

fromthemoonx added a commit to fromthemoonx/Leonida that referenced this pull request Nov 23, 2026
…pk_fmac_f16

9d71037 (ItsNotRexed#3220) widened f16 operands exactly in Gen.f16_in because NVIDIA read
an SDWA-selected denormal as 0. v_cvt_f32_f16, v_pk_fma_f16 and v_pk_fmac_f16
still widen with UnpackHalf2x16 directly, and no GPU fixture fed them a
denormal. cs_w32_f16_denorm_widen does: denormals from a VGPR, a literal and an
SDWA WORD_1 select, as multiplicands, addends and the fmac accumulator, plus a
normal control word. Expected words follow from RDNA2 keeping f16 denormals.

Registered in check.py and run_gpu_tests.py (wave32 dump), in
regen_fixtures.py, and run on the CPU by test_f16_denorm_widen_fixture.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FXR27ZYP9qtZtN8SG7QPWW
@ItsNotRexed
ItsNotRexed merged commit 7c6fc72 into ItsNotRexed:main Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.