Skip to content

Shaders: lower binary64 square root with 32-bit operations - #2791

Open
andrewpozdnakov7-jpg wants to merge 3 commits into
Marvisak:mainfrom
andrewpozdnakov7-jpg:codex2/sqrt-f64
Open

andrewpozdnakov7-jpg wants to merge 3 commits into
Marvisak:mainfrom
andrewpozdnakov7-jpg:codex2/sqrt-f64

Conversation

@andrewpozdnakov7-jpg

Copy link
Copy Markdown
Contributor

Main stops translation on V_SQRT_F64. The lowering normalizes the two-word significand, computes 24 root bits with integer arithmetic, and applies the known rounding mode. It handles subnormals according to the known input-denormal mode, preserves signed zeros and positive infinity, and quiets NaNs. The DXIL requires only 32-bit operations. AMD specifies an accuracy bound of 2^29 binary64 ULP for this instruction. RDNA 2 ISA reference

Both synthetic readbacks fail on 13f91ca with unsupported v_sqrt_f64. The same fixtures pass all 107 cases on app-local WARP SM 6.6 with the DXIL validator. They exercise VOP1 VGPR and VOP3 SGPR sources, all four rounding modes, a flush-input mode, special values, and the cross-dword normalization boundary. They also check the DXIL feature flags for optional doubles and int64. An independent integer model stayed within the specified bound in 262,016 comparisons against CPU binary64 square roots across all finite exponent fields.

The full serial shader suite moved from 268 passed, 5 failed, and 3 ignored to 270 passed, 3 failed, and 3 ignored with both new tests present. The same gather-at-level, lane-permute, and edge-flagged triangle tests failed on both revisions. All 33 VALU tests in the patched run passed, including the runtime identity check. Strict shader Clippy and staged asset policy passed.

This uses the same FP16/FP64 mode analysis as #2743. Coordination claim

Please retain the Git author on cherry-pick or rebase. If you fold this change into another commit, please include Co-authored-by: andrewpozdnakov7-jpg <andrewpozdnakov7-jpg@users.noreply.github.com>.

@kotekompotek

Copy link
Copy Markdown

Stacked on the same FpMode16 refactor as #2743 (same author, codex2/* series) - the base reads consistently, and the sqrt approach (normalize the two-word significand, 24 root bits via integer ops, apply tracked rounding mode, handle subnormals per denorm mode) is the right way to do binary64 in 32-bit DXIL. The 2^29 ULP bound quoted is AMD's own sqrt_f64 spec, so matching it is the correct bar. Same merge-order note as #2743: whichever of this/#2743/#2782 lands second touches mode16.

@oni-swr

oni-swr commented Nov 25, 2026

Copy link
Copy Markdown

WARP/CPU verification of head 8a53189143333bd54ecf2ae65885d581ccb36151

Environment: Windows 11 x64, rustc/cargo 1.98.1, WARP/CPU only (VICTORY_WARP=1, VICTORY_D3D12_WARP=1), no physical GPU, no game files. DXIL validation with Windows SDK 10.0.26100.0 x64 dxil.dll 1.8.2502.11. PR head merged cleanly onto origin/main 13f91ca.

Tests (cargo test --no-fail-fast -p victory-shader)

  • origin/main baseline: 267 passed, 3 failed, 3 ignored.
  • With this PR: 269 passed, 3 failed, 3 ignored (+2: sqrt_f64_tracks_binary64_range_and_rounding, sqrt_f64_preserves_signed_zero_when_mode_flushes_subnormals).
  • The 3 failures are the same on origin/main and unrelated to this PR: a_mask_joined_with_data_at_a_uniform_loop_is_its_number, gathers_at_a_level_match_the_hardware, permutes_read_the_lane_named_and_zero_from_lanes_left_out (they compare against hardware lane results and fail on WARP).

Negative control (each mutation applied alone, then reverted, new tests only)

  • v_sqrt_f64 dispatch removed: both new tests fail.
  • Rounding increment disabled (if false && matches!(mode, 0 | 1)): range/rounding test fails.
  • Signed-zero result replaced by +0: both new tests fail.

Lint: cargo clippy --all-targets -- -D warnings clean. cargo fmt --check: +3 hunks in crates/victory-shader/src/emit/lower.rs (28 on main, 31 with the PR), all in the new FpMode16 block (INITIAL, the s_round_mode/s_denorm_mode arms, and the final Self { round: update(..), .. }); sqrt.rs and valu_tests.rs add none. Note: cargo fmt --check is already red on origin/main here (891 hunks, none from these PRs), so I compared per-file hunk counts against that baseline.

Review: read the full diff. The MODE bits 3:2 / 7:6 tracking with per-field join is correct, and the sqrt lowering handles sign, abs/neg, non-finite, and subnormal operands (flush vs preserve) coherently. The tests check the 2^29-ULP bound and rounding direction, not bit-exactness against hardware, and I did not run any hardware. No game files, dumps, shader names, or retail hashes in the diff.

AI disclosure: this verification was done by Claude Code (Claude Sonnet 5.5).

@fuzeofficlal

Copy link
Copy Markdown
Contributor

Reviewed and verified 8a531891 on Windows 11 (RTX 5090 + WARP + Windows SDK 10.0.26100.0 dxil.dll) against main (13f91ca).

Code review

  • Pure 32-bit DXIL lowering (SFI0 & 0x8001 == 0, no double/int64 capability needed).
  • Special cases and MODE[7:6] denorm handling check out cleanly: ±0.0 preserved, negative finite / -Inf -> canonical qNaN 0xfff8_0000_0000_0000, sNaN quietened with payload intact (including low-word-only payloads), input subnormal flush (-denorm -> -0.0) vs. FirstbitHi cross-dword normalization, and 24-bit integer square-root iteration across all 4 rounding modes (RNE/RTP/RTN/RTZ) meeting RDNA2's 2^29 ULP bound.
  • Cross-PR merge notes:
    • Clean git merge-tree vs 13f91ca, #2713, #2728, and #2782; conflicts in lower.rs with #2743 (both introduce the identical FpMode16 / fp_modes16 refactor).
    • Semantic compile interaction with #2782: even though git merge-tree with #2782 is textually clean, changing Lower::mode16 from Option<u8> to FpMode16 { round, denorm } means #2782's self.mode16.ok_or(...) (lower.rs:3384) will need to become self.mode16.round.ok_or(...) when both land.

Verification (Windows 11, RTX 5090 + WARP + dxil.dll)

  • cargo test --locked -p victory-shader --features host --lib -- valu_tests::: 32 passed, 0 failed (both new sqrt_f64_* tests pass on RTX 5090 and WARP with dxil.dll).
  • cargo clippy --locked -p victory-shader --all-targets -- -D warnings (default & --features host): 0 warnings; cargo xtask policy: 185 files ok.

Copy link
Copy Markdown
Owner

Automated triage for the maintainers.

This PR replaces the round-only round16 analysis in crates/victory-shader/src/emit/lower.rs with FpMode16, which tracks MODE bits 3:2 and 7:6 with a per-field join. It also lowers v_sqrt_f64 (lower/sqrt.rs, sqrt_f64) with 32-bit integer operations to the 2^29 ULP bound the public RDNA2 ISA reference gives for V_SQRT_F64. I checked the s_round_mode/s_denorm_mode/s_setreg bit extraction, the join, and the special-value ordering (zero overrides the negative-NaN path, so sqrt(-0) = -0). Input-denormal flushing uses bit 6, as the ISA defines. CI passes.

Notes for the maintainer:

This is a recommendation for a maintainer to look, not an approval.


Generated by Claude Code

@Dukestar69 Dukestar69 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Tested merged onto origin/main (63bcca4) on Windows 11 x64 (NVIDIA GeForce RTX 5090 + WARP, dxil.dll validator active):

  • cargo test -p victory-shader --lib emit::valu_tests::sqrt: 2 passed, 0 failed (sqrt_f64_preserves_signed_zero_when_mode_flushes_subnormals and sqrt_f64_tracks_binary64_range_and_rounding pass on both RTX 5090 hardware and WARP).
  • cargo clippy -p victory-shader --all-targets -- -D warnings: clean.
  • cargo xtask policy: 192 files ok.

Synthetic tests only (no game files used). AI-assisted (Gemini 4 Neon).

@fuzeofficlal fuzeofficlal left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nice 32-bit fixed-point v_sqrt_f64 implementation — the 24-bit digit-recurrence math, rounding (within 2^28 ULP for RTE and 2^29 ULP for directed modes), special cases (including -0.0, NaN quietening/payloads, abs/neg, and all source kinds), and SFI0 (0x8001 == 0) check out cleanly. emit::valu_tests::sqrt (2/2 on RTX 5090 and WARP), emit::lower::tests (33/33), clippy, and xtask policy all pass, and sqrt.rs / the new valu_tests.rs lines pass rustfmt.

One live-reproduced silent miscompilation in FpMode16 tracking needs fixing before merge (plus two smaller items):

  1. MODE writes inside whole-wave sections are skipped during lowering (crates/victory-shader/src/emit/lower.rs:1383-1389)

    • When self.sections runs section_inst for j in i + 1..end and jumps i = end, self.mode16 is not updated across i + 1..end (even though fp_modes16 does walk every instruction in block order).
    • Reproduced on hardware (RTX 5090): placing s_denorm_mode 8 (flush FP16/FP64 inputs) between s_or_saveexec_b32 and the exec restore left a subsequent v_sqrt_f64 in the same block using stale preserve mode, returning 0x1e60_0000_0000_0000 and 0xfff8_0000_0000_0000 for 1 and SIGN | 1 instead of +0.0 and -0.0. Updating self.mode16 across the skipped section instructions fixes this.
  2. Partial-field MODE writes and mode 1/3 joins drop known input-denorm state (lower.rs:311-333)

    • s_setreg_imm32_b32 hwreg(MODE, 7, 1), 0 writes only bit 7 (output denorm flush), leaving bit 6 (input denorm preserve) unchanged, yet FpMode16::after requires offset <= start && end >= start + 2 and otherwise resets the entire denorm field to None. Similarly, joining paths with denorm = 1 and denorm = 3 loses the shared input-denorm bit.
    • Reproduced: a shader with s_setreg_imm32_b32 hwreg(MODE, 7, 1), 0 before v_sqrt_f64 fails to lower with binary64 square root with unknown floating-point modes, even though sqrt_f64 only depends on the input-denorm bit (denorm & 1). Tracking the input-denorm bit independently (or merging partial literal bitfield updates) avoids rejecting valid shaders.
  3. Minor formatting (lower.rs:296, :303, :319)

    • rustfmt --edition 2024 --check flags line wrapping on the added FpMode16 methods at crates/victory-shader/src/emit/lower.rs:296, :303, and :319.

@andrewpozdnakov7-jpg

andrewpozdnakov7-jpg commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor Author

The follow-up ce63f02 carries MODE updates across whole-wave sections and tracks the input-denormal bit independently. A write to the output-denormal bit and a join of input-preserving modes now retain the known input mode.

On the previous head, the synthetic whole-wave case returned nonzero/NaN for signed subnormal inputs that should flush to signed zero. The partial output-only write was rejected as an unknown mode. On the updated head, both regressions and the two existing binary64 square-root tests passed on app-local WARP with DXIL validation. Strict shader Clippy passed in the default and all-features configurations.

Ready for another review. If reused, please retain Git authorship when cherry-picking or rebasing. If folded into another commit, please add Co-authored-by: andrewpozdnakov7-jpg <andrewpozdnakov7-jpg@users.noreply.github.com>.

AI-assisted with Codex. Synthetic shaders only.

I also resolved the merge overlap with #2782 in b0dab3c on current main 63bcca4. The scalar MODE read and sqrt use a shared mode state in that tree. All 42 VALU tests passed on app-local WARP.

@andrewpozdnakov7-jpg

Copy link
Copy Markdown
Contributor Author

Thanks @fuzeofficlal. The three cases from your review reproduced on f30cf4e: flushing inside a whole-wave section left the two signed subnormal results wrong, and the output-only write and the 1/3 join both made the input mode unknown. The current ce63f02 addresses these cases.

I also checked the interaction you called out with #2782. The combined branch carries both published heads on main 63bcca4, preserving their commits. Its integration resolves the whole-wave update once through FpMode16::after and reads self.mode16.round for s_getreg_b32. I ran both sides of the 1/3 join with distinct subnormal inputs.

WARP passed all 42 VALU tests, including the sqrt and MODE-read cases. Strict all-features shader Clippy and asset policy passed on the combined tree. The branch is available for the second PR's rebase when the first lands.

AI-assisted with Codex. Synthetic shaders only.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants