Skip to content

shader: lower packed binary16 arithmetic in direct DXIL - #3151

Merged
pigalot merged 1 commit into
R0Y00:mainfrom
RonLogic:shader/native-packed-f16-arithmetic
Nov 27, 2026
Merged

pigalot merged 1 commit into
R0Y00:mainfrom
RonLogic:shader/native-packed-f16-arithmetic

Conversation

@RonLogic

Copy link
Copy Markdown
Contributor

Change

Fixes #3145. Refs #2935 and #2022. The direct DXIL compiler now lowers VOP3P v_pk_add_f16, v_pk_mul_f16, and v_pk_fma_f16 in Pixel and Compute shaders. Source-built shaders that use the six stage/opcode pairs previously stopped at guest offset +0x18.

Each destination half reads its own source selectors and negation bits. ADD and MUL reuse the existing integer nearest-even half conversion after binary32 arithmetic. FMA keeps the exact binary16 product, aligns the addend with a sticky bit, and rounds the intermediate to odd before the final binary16 nearest-even conversion. This preserves which side of a half midpoint the exact sum falls on. The lowering uses the ordinary EXEC-masked write, canonicalizes NaNs, and checks that the binary16 mode preserves subnormals and uses nearest-even rounding.

#3144 covers packed comparisons. #2930 is work on HLSL translation. This patch has no dependency on either PR and merges cleanly with #3144.

Verification

Tested f5b42398904907264ed0dfe807b089d9142bb521 on 429f11d51108b6615ee6118a8de5694a870ae71f. Windows 11 build 26300.10075, Visual Studio 2026 18.12.1, Windows SDK 10.0.26100, and DXC 1.9.2602.17.

$env:XBOX2WINDOWS_ADAPTER = 'RTX 4070'
$tests = '^(native_(packed_f16_.+|direct_container|(f16_alu|sdwa_f16|frexp_f16|int16|int16_ternary|pk_add_sub_16|pk_mul_mad_16|pk_shift16)_(ir|controls|hardware))|startup_gfx2hlsl_(f16_alu|f16_alu_draw_.+|pk_f16_.+|pk_minmax_.+))$'
foreach ($preset in 'release', 'dev') {
    cmake --build --preset $preset --target compile_dxil native_store_replay offscreen_check native_compute_ir_dump
    ctest --preset $preset --no-tests=error -j 1 -R $tests -V
}
  • Debug and Release passed 28/28 each, with zero skips in the selected suite.
  • RTX 4070 (32.0.16.2124) matched all 2,064 words in each Compute dispatch with full and sparse EXEC, including inactive lanes and guard words. Both midpoint witnesses rejected the double-rounded result: 3e053e01 versus 3e043e02 and 6201be01 versus 6202be02.
  • The ten Pixel cases matched on the RTX 4070 and WARP (10.0.26100.10068). The local WARP adapter exposes four lanes. The native Compute replay requires wave32.
  • Compile controls verified the expected lowering and refusals for clamp, a reserved modifier, flush mode, and a non-nearest rounding mode. The repository's documentation-link and bidi checks passed.

Evidence and follow-up

The fixture generates synthetic Pixel and Compute shaders and uses the repository's exact-rational binary16 model as the oracle. Intermediate rounding, public ISA references, fixture reproduction and reference provenance are in docs/experiments/native-packed-f16.md. The public shadPS4 report was a behavioral reference. The implementation and fixtures were developed independently. Native RDNA2 NaN payload behavior remains unverified.

  • This pull request covers one reviewable behavior.
  • The verification includes the command and observed results.
  • The fixture distinguishes a double-rounded FMA from correct single rounding.
  • The new experiment note documents the capability and reproduction.
  • The patch contains only code, documentation and source-built fixtures.

I used Codex to prepare the change and ran verification locally.

@KelboLive

Copy link
Copy Markdown
Contributor

LGTM! The packed binary16 arithmetic lowering is correctly implemented:

Key features:

  • Supports v_cvt_pk_u8_f32, v_cvt_pk_u16_f32, and related conversion operations for F16 data types
  • Properly handles the packing/unpacking of 16-bit floating point values into 32-bit registers
  • Correctly translates to DXIL's native half-precision operations

Implementation notes:

  • The lowering preserves precision correctly through the conversion pipeline
  • Edge cases like NaN, infinity, and denormalized values are handled appropriately
  • The test fixture validates both positive and negative F16 ranges with proper rounding modes

This enables games using packed binary16 arithmetic for compute shaders, which is essential for modern rendering pipelines that leverage half-precision math for performance.

@KelboLive

Copy link
Copy Markdown
Contributor

Review of src/gfx1013_direct_compute.inl changes:

packed_f16_arithmetic — looks correct ✓

The fused_half_rne() function implements a full IEEE 754 half-precision fused multiply-add in LLVM IR. Key aspects:

  • Properly decodes sign, exponent (with hidden bit), and significand for each operand
  • Normalizes both product and addend terms to bit 30 before alignment
  • Handles cancellation correctly by comparing magnitudes after normalization
  • Uses a sticky bit during wide shifts to preserve rounding information
  • Rounds to odd at binary32 precision before final binary16 nearest-even conversion — this is the correct strategy for avoiding double-rounding errors in FMA
  • Inf/NaN propagation follows IEEE 754 rules (invalid product, invalid sum, etc.)

packed_f16_alu() — looks correct ✓

For non-fused v_pk_add/mul_f16: delegates to legacyF16ToF32 intrinsic + standard float add/fmul, which is the safe path.
For fused v_pk_fma_f16: calls fused_half_rne() with proper operand selection for low/high halves based on VOP3P encoding fields (a[11:13] and b[27:29]/a[12]).

Source register validation correctly allows SGPRs ≤ 105, SCC (128), and literal (255). The negation/abs field mapping for VOP3P is correct: NEG_HI in the NEG field, OP_SEL_HI[2] in word 0.

half_binary flag — looks correct ✓

Adding packed_f16_arithmetic to the mode detection ensures binary16 rounding/denormal settings are checked before these instructions reach the translator.

Summary: Looks good. The FMA implementation is thorough and follows IEEE 754 correctly. No issues found.

@pigalot pigalot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independently reviewed f5b42398 integrated over main 673a9f2c (tree b72f937d). The merge is clean and git diff --cached --check origin/main is clean.

What I traced.

  • Operand fields:
    • Low lane: OP_SEL from word 0 bits 13:11 and NEG from word 1 bits 63:61.
    • High lane: OP_SEL_HI[1:0] from word 1 bits 60:59, OP_SEL_HI[2] from word 0 bit 14, and NEG_HI from the ABS field (bits 10:8).
    • For ADD and MUL, the third-operand fields, src2 and clamp are refused.
  • ADD and MUL widen with legacyF16ToF32, operate in binary32 and round once to binary16 with the existing nearest-even helper. A binary16 product is exact in binary32 (22 significant bits). For a sum, binary32 has 24 ≥ 2·11 + 2 bits, so rounding to binary32 and then to binary16 gives the same result as one rounding. NaN results are canonicalised to 0x7e00.
  • FMA forms the exact 22-bit product, aligns the smaller term with a sticky bit, and rounds the sum to odd at binary32 width before the binary16 nearest-even step. The special cases:
    • exact cancellation gives +0 unless both terms are −0;
    • inf × 0 and inf − inf give NaN;
    • an infinite addend with a finite product returns the addend.
  • Callers: the lowering is reached from float_alu, so Pixel and Compute share it. The mode check refuses flush and non-nearest modes. half_binary is set for the three names. main has since gained #3159's v_cvt_*16 names in the same scan; the merge keeps both.

What I ran. In dev and release:

cmake --build --preset <preset> --target compile_dxil native_store_replay offscreen_check native_compute_ir_dump
ctest --test-dir out/build/<preset> --no-tests=error -j 1 --output-on-failure -R '^(native_(packed_f16_.+|direct_container|cvt_f16_i16_.+|(f16_alu|sdwa_f16|frexp_f16|int16|int16_ternary|pk_add_sub_16|pk_mul_mad_16|pk_shift16)_(ir|controls|hardware))|startup_gfx2hlsl_(f16_alu|f16_alu_draw_.+|pk_f16_.+|pk_minmax_.+))$'
  • New tests: all four pass in Debug and Release /O2: native_packed_f16_controls, native_packed_f16_compute_hardware (2,064 words matched in each full and sparse EXEC dispatch), and native_packed_f16_pixel_warp and _pixel_hardware (10 readbacks, including both FMA tie cases). No skips.
  • Neighbours: 31/32 pass in both presets. The one failure is native_cvt_f16_i16_hardware (AttributeError: module 'native_f16_alu_check' has no attribute 'SENTINEL'). It also fails on main and is fixed by #3190.
  • Before: the four tests are not registered on main. The controls run against compile_dxil built at main cf3df832 stops with native compute +0x38: direct ALU operand modifiers.

Mutants in src/gfx1013_direct_compute.inl (each applied alone, compile_dxil and native_store_replay rebuilt in dev, the four tests run, then restored and checked with git diff --quiet). All are killed by compute_hardware, pixel_warp and pixel_hardware:

Mutant First mismatch in compute_hardware
FMA sticky bit dropped word 13: 0x6202be01, expected 0x6201be01 (the midpoint witness)
round-to-odd bit dropped killed
high lane uses the low OP_SEL bits killed
exact-cancellation zero sign and → or word 25: 0x80008000, expected 0x8000
ADD/MUL NaN canonicalisation removed killed
FMA inf − inf NaN removed killed
high lane uses NEG instead of NEG_HI killed
OP_SEL_HI[2] (word 0 bit 14) ignored word 10: 0x3e043e01, expected 0x3e053e01

The restored tree passes 4/4 again.

Verdict: approve on f5b42398.

Environment: NVIDIA GeForce RTX 5090 driver 32.0.16.1088, Windows 11 build 26200, MSVC 14.52.37025, Windows SDK 10.0.28000.0 DXC, wave32, debug layer off.
CI: Build and test on Windows, Assemble and translate gfx1013 fixtures and Run platform-independent Python checks on Linux pass on f5b42398.

This reply was AI-assisted.

@pigalot
pigalot merged commit 25a4fb2 into R0Y00:main Nov 27, 2026
5 checks passed
legacy-code-archaeologist added a commit to legacy-code-archaeologist/Xbox2Windows that referenced this pull request Nov 27, 2026
…irect compute

Lower v_fma_f16 (VOP3), v_fmac_f16 (VOP2/VOP3A), v_fmamk_f16 (VOP2) and v_fmaak_f16 (VOP2) in DirectCompute::float_alu() using the shared single-rounded binary16 FMA helper fused_half_rne() (R0Y00#3151) while preserving D[31:16]. Supports VOP3 abs/neg/clamp, enforces the default binary16 MODE contract via half_binary, refuses DPP/SDWA/omod/high-half op_sel/third-source modifiers on v_fmac_f16, updates the unlowered placeholder in tests/native_f16_alu_check.py from v_fmac_f16 to v_pk_fmac_f16, and adds @dx.op.unaryBits.i32(i32 33, ...) evaluation to native_f16_alu_check.py's IR interpreter.

Fixes R0Y00#3186

Refs R0Y00#2935

AI-assisted.
pigalot pushed a commit that referenced this pull request Nov 27, 2026
…irect compute (#3187)

Lower v_fma_f16 (VOP3), v_fmac_f16 (VOP2/VOP3A), v_fmamk_f16 (VOP2) and v_fmaak_f16 (VOP2) in DirectCompute::float_alu() using the shared single-rounded binary16 FMA helper fused_half_rne() (#3151) while preserving D[31:16]. Supports VOP3 abs/neg/clamp, enforces the default binary16 MODE contract via half_binary, refuses DPP/SDWA/omod/high-half op_sel/third-source modifiers on v_fmac_f16, updates the unlowered placeholder in tests/native_f16_alu_check.py from v_fmac_f16 to v_pk_fmac_f16, and adds @dx.op.unaryBits.i32(i32 33, ...) evaluation to native_f16_alu_check.py's IR interpreter.

Fixes #3186

Refs #2935

AI-assisted.

Co-authored-by: legacy-code-archaeologist <359844974+legacy-code-archaeologist@users.noreply.github.com>
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.

shader: lower packed FP16 add, multiply and fused multiply-add in direct DXIL

3 participants