perf(shader): convert v_cvt_pkrtz_f16_f32 from the native nearest-even conversion #2411

Merged
karanvora2599 merged 3 commits from upstream-pr/2411 into main 2026-10-11 08:41:08 +00:00
karanvora2599 commented 2026-10-09 18:29:30 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by karanvora2599 on 2026-10-09T18:29:30Z.


What

v_cvt_pkrtz_f16_f32 packs two f32 values as halves rounded toward zero. It is converted with integer operations today; on devices where #1252 converts f32 to f16 natively, this builds the toward-zero conversion from that native nearest-even conversion plus a one-step correction. Results are bit-identical; on an RTX 4060 the instruction drops from 32.5 to 18.5 instructions. Devices without #1252's guarantees keep the integer conversion.

#1252 is merged, and this branch has current main merged in, so the diff is only this change.

Background

  • RDNA rounds v_cvt_pkrtz_f16_f32 toward zero regardless of the shader's rounding mode: finite values truncate to the half below them in magnitude, values from 65536 up become 65504 (0x7bff), infinities stay infinite, NaNs become sign | 0x7e00 | mantissa >> 13 (EmitF32ToF16RtzBits), f32 denormal inputs are flushed (#1850) and, in the f16 denormal mode titles use, f16 subnormal results are kept.
  • Pixel shaders use it to pack two color channels per dword for compressed exports, so it appears in many pixel shaders.
  • No NVIDIA driver can be asked for an RTZ f16 conversion: shaderRoundingModeRTZFloat16 is false on every NVIDIA driver, and an FPRoundingMode decoration on OpFConvert is only valid when the result is stored straight to 16-bit StorageBuffer/PhysicalStorageBuffer/Uniform/Output memory. So the toward-zero half has to be built in the shader.

Before

EmitF32ToF16RtzBits (SpirvBackend/src/SpirvModuleEmitter.cpp) splits the f32 into sign, exponent and mantissa, builds the normal and the subnormal half and the NaN and infinity patterns, and picks among them with exponent compares: about 30 SPIR-V instructions per half.

After

On devices with #1252's 16-bit RoundingModeRTE, DenormPreserve and SignedZeroInfNanPreserve (where EmitF32ToF16BitsRte uses OpFConvert), each half is:

  1. h = EmitF32ToF16BitsRte(x): the nearest-even half, with #1252's NaN result;
  2. back = OpFConvert(f32, h), exact;
  3. |back| > |x| ? h - 1 : h.

Why the results don't change

  • A finite x lies between two consecutive halves (or above 65504). The nearest-even conversion returns one of the two, and |back| > |x| exactly when it returned the one further from zero. One step down in the half's bits (sign and magnitude) is then the other one, also across a power of two and from the smallest subnormal to ±0.
  • That covers f16 subnormal results (kept by DenormPreserve 16), x from 65520 up (nearest even gives infinity, one step down is 65504) and small negative x (0x8001 steps to -0).
  • An infinite x converts to itself, back equals x, and it stays infinite.
  • For a NaN, #1252's result is sign | 0x7e00 | mantissa >> 13, the same bits as EmitF32ToF16RtzBits; the ordered compare is false, so it isn't stepped.
  • x has already been through the f32 denormal flush, and back is a normal f32 or zero, so the compare never sees an f32 denormal: a driver that flushes them gives the same result.

Alternative measured

Truncating each value to a representable half first (x & 0xffffe000, trunc(x * 2^24) * 2^-24 below 2^-14, ±65504 above the range, the NaN kept) and then converting needs no conversion back, but costs 28.5 instructions on the same GPU instead of 18.5. The version here relies on the driver keeping the f32 → f16 → f32 round trip; a value-changing optimization could fold it to the identity (dxil-spirv notes NVIDIA drops packHalf2x16/unpackHalf2x16 pairs). The driver tested here keeps it, and the new test would fail on a device that folds it, as the negative check below shows.

Where it matters

Every pixel shader that packs its colors with v_cvt_pkrtz_f16_f32, on devices with the three 16-bit guarantees (NVIDIA Turing and newer report them; Pascal has no shaderFloat16). Only an Ada GPU (sm_89) was measured.

Tested

Windows 11, MinGW-w64 GCC 15.2.0 (WinLibs r7), Release, ANYPS5_ENABLE_SPIRV_TOOLS=ON, main at f8c2f072 with #1252's commit. GPU tests on an NVIDIA GeForce RTX 4060 Laptop GPU (driver 591.86, subgroup 32), which has the three 16-bit guarantees and takes the new path, and on lavapipe (Mesa 26.2.4 for Windows, GALLIUM_OVERRIDE_CPU_CAPS=avx), which reports shaderDenormPreserveFloat16 = 0 and keeps the integer conversion.

Correctness

  • New agc_driver_f16_pack_toward_zero: v_cvt_pkrtz_f16_f32 x, -x (VOP3, negated second source) over 158,752 inputs in one dispatch (FLOAT_MODE 0xc0):

    • every finite half as an f32, the next f32 above it, the midpoint to the next half and the f32 on each side of that midpoint;
    • 0, f32 denormals, 2^-126, 2^-25 and its neighbours, 2^-24, 2^-14 and the f32 below it;
    • 65504, 65519.99, 65520, 65536, FLT_MAX, infinities;
    • quiet and signaling NaNs with payloads in the high and in the low mantissa bits.

    Expected halves come from truncating the f32 bits on the host, with the rules of EmitF32ToF16RtzBits. It passes on both devices, so the new path (RTX 4060) and the integer conversion (lavapipe) agree on all of them.

  • Negative check: without the step toward zero (the nearest-even half only), the RTX 4060 fails with f16 pack toward zero: v_cvt_pkrtz_f16_f32 of 0x33000001, -0x33000001 is 0x80010001, expected 0x80000000; lavapipe, on the integer conversion, still passes. The test reaches the new path.

  • #1252's agc_float16_conversion and the f16 execution tests (agc_driver_float16_*, including the v_cvt_pkrtz_f16_f32 rows of agc_driver_float16_result_modifiers) pass on both devices.

  • Every shader test (agc_driver_*, agc_shader_*, agc_spirv_*, vector_*, agc_float16_*, agc_masked_select, agc_validate_program, 236 tests): all pass on the RTX 4060 (1 skipped, agc_driver_storage_cache_budget); on lavapipe 210 pass and 26 are skipped for missing device features.

Instructions per op (RTX 4060, not committed)

Method: a wave32 compute program with a dependent chain of 16 v_xor_b32 + <op> steps (the xor keeps the compiler from folding the chain), recompiled with FLOAT_MODE 0xc0 and created with APS5_PIPELINE_STATS=1; "Binary Size" / 16 bytes per instruction, compared with the same chain of v_add_nc_u32 steps.

main this branch
v_cvt_pkrtz_f16_f32 (this PR) 32.5 18.5
v_cvt_f16_f32 (#1252's commit, for reference) 37.5 11.5
v_add_f16 (#1252's commit, for reference) 38 11.5

Cost of #1252's float-controls modes on f32 code (RTX 4060, not committed)

Several projects report that some float-controls execution modes slow f32 code on NVIDIA, so this checks the 16-bit RoundingModeRTE, DenormPreserve and SignedZeroInfNanPreserve modes #1252 adds to a module that converts to f16. A chain of 1024 v_fma_f32 (or alternating v_fma_f32/v_add_f32) followed by one v_cvt_f16_f32 is timed against the same chain without the conversion, back to back in one process, 12 rounds. The ratio is the same with and without #1252 (0.95 and 0.95; 1.00 and 1.00, medians), and the f32 chain compiles to the same size. No effect on f32 code was measurable here.

The measurement programs aren't part of this PR; I can attach them if useful.

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed in TechnicalDebt
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: none (#1252 is merged)
  • AI-assisted: yes
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4804354940 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/2411). Originally posted by [karanvora2599](https://github.com/karanvora2599) on 2026-10-09T18:29:30Z. --- ### What `v_cvt_pkrtz_f16_f32` packs two f32 values as halves rounded toward zero. It is converted with integer operations today; on devices where #1252 converts f32 to f16 natively, this builds the toward-zero conversion from that native nearest-even conversion plus a one-step correction. Results are bit-identical; on an RTX 4060 the instruction drops from 32.5 to 18.5 instructions. Devices without #1252's guarantees keep the integer conversion. #1252 is merged, and this branch has current `main` merged in, so the diff is only this change. #### Background - RDNA rounds `v_cvt_pkrtz_f16_f32` toward zero regardless of the shader's rounding mode: finite values truncate to the half below them in magnitude, values from 65536 up become 65504 (`0x7bff`), infinities stay infinite, NaNs become `sign | 0x7e00 | mantissa >> 13` (`EmitF32ToF16RtzBits`), f32 denormal inputs are flushed (#1850) and, in the f16 denormal mode titles use, f16 subnormal results are kept. - Pixel shaders use it to pack two color channels per dword for compressed exports, so it appears in many pixel shaders. - No NVIDIA driver can be asked for an RTZ f16 conversion: `shaderRoundingModeRTZFloat16` is false on every NVIDIA driver, and an `FPRoundingMode` decoration on `OpFConvert` is only valid when the result is stored straight to 16-bit `StorageBuffer`/`PhysicalStorageBuffer`/`Uniform`/`Output` memory. So the toward-zero half has to be built in the shader. #### Before `EmitF32ToF16RtzBits` (`SpirvBackend/src/SpirvModuleEmitter.cpp`) splits the f32 into sign, exponent and mantissa, builds the normal and the subnormal half and the NaN and infinity patterns, and picks among them with exponent compares: about 30 SPIR-V instructions per half. #### After On devices with #1252's 16-bit `RoundingModeRTE`, `DenormPreserve` and `SignedZeroInfNanPreserve` (where `EmitF32ToF16BitsRte` uses `OpFConvert`), each half is: 1. `h = EmitF32ToF16BitsRte(x)`: the nearest-even half, with #1252's NaN result; 2. `back = OpFConvert(f32, h)`, exact; 3. `|back| > |x| ? h - 1 : h`. #### Why the results don't change - A finite `x` lies between two consecutive halves (or above 65504). The nearest-even conversion returns one of the two, and `|back| > |x|` exactly when it returned the one further from zero. One step down in the half's bits (sign and magnitude) is then the other one, also across a power of two and from the smallest subnormal to `±0`. - That covers f16 subnormal results (kept by `DenormPreserve` 16), `x` from 65520 up (nearest even gives infinity, one step down is 65504) and small negative `x` (`0x8001` steps to `-0`). - An infinite `x` converts to itself, `back` equals `x`, and it stays infinite. - For a NaN, #1252's result is `sign | 0x7e00 | mantissa >> 13`, the same bits as `EmitF32ToF16RtzBits`; the ordered compare is false, so it isn't stepped. - `x` has already been through the f32 denormal flush, and `back` is a normal f32 or zero, so the compare never sees an f32 denormal: a driver that flushes them gives the same result. #### Alternative measured Truncating each value to a representable half first (`x & 0xffffe000`, `trunc(x * 2^24) * 2^-24` below 2^-14, `±65504` above the range, the NaN kept) and then converting needs no conversion back, but costs 28.5 instructions on the same GPU instead of 18.5. The version here relies on the driver keeping the f32 → f16 → f32 round trip; a value-changing optimization could fold it to the identity (dxil-spirv notes NVIDIA drops `packHalf2x16`/`unpackHalf2x16` pairs). The driver tested here keeps it, and the new test would fail on a device that folds it, as the negative check below shows. #### Where it matters Every pixel shader that packs its colors with `v_cvt_pkrtz_f16_f32`, on devices with the three 16-bit guarantees (NVIDIA Turing and newer report them; Pascal has no `shaderFloat16`). Only an Ada GPU (sm_89) was measured. ### Tested Windows 11, MinGW-w64 GCC 15.2.0 (WinLibs r7), Release, `ANYPS5_ENABLE_SPIRV_TOOLS=ON`, `main` at f8c2f072 with #1252's commit. GPU tests on an NVIDIA GeForce RTX 4060 Laptop GPU (driver 591.86, subgroup 32), which has the three 16-bit guarantees and takes the new path, and on lavapipe (Mesa 26.2.4 for Windows, `GALLIUM_OVERRIDE_CPU_CAPS=avx`), which reports `shaderDenormPreserveFloat16 = 0` and keeps the integer conversion. **Correctness** - New `agc_driver_f16_pack_toward_zero`: `v_cvt_pkrtz_f16_f32 x, -x` (VOP3, negated second source) over 158,752 inputs in one dispatch (`FLOAT_MODE` 0xc0): - every finite half as an f32, the next f32 above it, the midpoint to the next half and the f32 on each side of that midpoint; - 0, f32 denormals, 2^-126, 2^-25 and its neighbours, 2^-24, 2^-14 and the f32 below it; - 65504, 65519.99, 65520, 65536, `FLT_MAX`, infinities; - quiet and signaling NaNs with payloads in the high and in the low mantissa bits. Expected halves come from truncating the f32 bits on the host, with the rules of `EmitF32ToF16RtzBits`. It passes on both devices, so the new path (RTX 4060) and the integer conversion (lavapipe) agree on all of them. - Negative check: without the step toward zero (the nearest-even half only), the RTX 4060 fails with `f16 pack toward zero: v_cvt_pkrtz_f16_f32 of 0x33000001, -0x33000001 is 0x80010001, expected 0x80000000`; lavapipe, on the integer conversion, still passes. The test reaches the new path. - #1252's `agc_float16_conversion` and the f16 execution tests (`agc_driver_float16_*`, including the `v_cvt_pkrtz_f16_f32` rows of `agc_driver_float16_result_modifiers`) pass on both devices. - Every shader test (`agc_driver_*`, `agc_shader_*`, `agc_spirv_*`, `vector_*`, `agc_float16_*`, `agc_masked_select`, `agc_validate_program`, 236 tests): all pass on the RTX 4060 (1 skipped, `agc_driver_storage_cache_budget`); on lavapipe 210 pass and 26 are skipped for missing device features. **Instructions per op** (RTX 4060, not committed) Method: a wave32 compute program with a dependent chain of 16 `v_xor_b32` + `<op>` steps (the xor keeps the compiler from folding the chain), recompiled with `FLOAT_MODE` 0xc0 and created with `APS5_PIPELINE_STATS=1`; "Binary Size" / 16 bytes per instruction, compared with the same chain of `v_add_nc_u32` steps. | | `main` | this branch | |---|---|---| | `v_cvt_pkrtz_f16_f32` (this PR) | 32.5 | 18.5 | | `v_cvt_f16_f32` (#1252's commit, for reference) | 37.5 | 11.5 | | `v_add_f16` (#1252's commit, for reference) | 38 | 11.5 | **Cost of #1252's float-controls modes on f32 code** (RTX 4060, not committed) Several projects report that some float-controls execution modes slow f32 code on NVIDIA, so this checks the 16-bit `RoundingModeRTE`, `DenormPreserve` and `SignedZeroInfNanPreserve` modes #1252 adds to a module that converts to f16. A chain of 1024 `v_fma_f32` (or alternating `v_fma_f32`/`v_add_f32`) followed by one `v_cvt_f16_f32` is timed against the same chain without the conversion, back to back in one process, 12 rounds. The ratio is the same with and without #1252 (0.95 and 0.95; 1.00 and 1.00, medians), and the f32 chain compiles to the same size. No effect on f32 code was measurable here. The measurement programs aren't part of this PR; I can attach them if useful. ### Checklist - [x] Based on current `main`; no other open PR implements the same functions - [x] One topic per PR; follow-ups go in a new PR - [x] No comments in code except [technical debt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/CONVENTIONS.md) - [x] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed in [TechnicalDebt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/TechnicalDebt.md#silent-stubs) - [x] No notes, investigation `.md` files or images added to the repository (attach them to this PR) - [x] New third-party code is a submodule built from source - [x] Generic behaviour, not specific to one title - [x] Depends on: none (#1252 is merged) - [x] AI-assisted: yes
github-actions[bot] commented 2026-10-09 18:29:41 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by github-actions[bot] on 2026-10-09T18:29:41Z.


Thank you for your interest in the project! We are sorry, but we cannot accept more PRs while we work through the existing backlog. This PR has been automatically closed and labeled "intake paused". This is not a judgment of the quality of your changes.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6086888855 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/2411#issuecomment-6086888855). Originally posted by [github-actions[bot]](https://github.com/apps/github-actions) on 2026-10-09T18:29:41Z. --- Thank you for your interest in the project! We are sorry, but we cannot accept more PRs while we work through the existing backlog. This PR has been automatically closed and labeled "intake paused". This is not a judgment of the quality of your changes.
adriadam10 commented 2026-10-11 08:41:05 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-11T08:41:05Z.


Checked on RADV (native path active): agc_driver_f16_pack_toward_zero passes over 158,752 inputs, and dropping the - 1 step makes it fail with 0x80010001, expected 0x80000000, so the test reaches the new path. Also compared v_cvt_pkrtz_f16_f32 on gfx1035 hardware (f32 denormals flushed, f16 denormals kept) with the test's model over the same inputs, NaN payloads included: no mismatches. Instruction counts on NVIDIA were not reproduced here. Merging.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6107227005 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/2411#issuecomment-6107227005). Originally posted by [adriadam10](https://github.com/adriadam10) on 2026-10-11T08:41:05Z. --- Checked on RADV (native path active): `agc_driver_f16_pack_toward_zero` passes over 158,752 inputs, and dropping the `- 1` step makes it fail with `0x80010001, expected 0x80000000`, so the test reaches the new path. Also compared `v_cvt_pkrtz_f16_f32` on gfx1035 hardware (f32 denormals flushed, f16 denormals kept) with the test's model over the same inputs, NaN payloads included: no mismatches. Instruction counts on NVIDIA were not reproduced here. Merging.
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
boykopovar/AnyPS5!2411
No description provided.