Skip to content

Shaders: lower v_div_scale_f32, v_div_fmas_f32 and v_div_fixup_f32 - #200

Open
n-romanovich wants to merge 1 commit into
Marvisak:mainfrom
n-romanovich:feat/valu-div-f32
Open

n-romanovich wants to merge 1 commit into
Marvisak:mainfrom
n-romanovich:feat/valu-div-f32

Conversation

@n-romanovich

Copy link
Copy Markdown

Implements IR tracking, lane-mask structuring, and DXIL lowering for RDNA2's IEEE-754 f32 division sequence (v_div_scale_f32, v_div_fmas_f32, v_div_fixup_f32) in victory-shader:

  • ir.rs & structure.rs: marks v_div_fmas_f32 (and v_div_fmas_f64) as reading VCC, and resolves VCC through lane-mask joins.
  • v_div_scale_f32: scales tiny/huge numerator or denominator operands by 2^64 / 2^-64 when needed (skipping 0, Inf, and NaN), writing the uncancelled scale flag to v.carry (lane_bits).
  • v_div_fmas_f32: computes fma(src0, src1, src2) and applies 2^64 / 2^-64 scaling based on VCC and src2's biased exponent (>= 128).
  • v_div_fixup_f32: handles IEEE-754 NaN propagation (quieting sNaNs), 0/0 & Inf/Inf (-NaN), division by zero / Inf, and result sign.

Testing

  • Added emit::tests::valu_div_f32_sequence_executes_on_gpu in crates/victory-shader/src/emit/mod.rs, running the full 9-instruction RDNA2 f32 division sequence across 6 lanes (7.0 / 3.0, -1.0 / 1e-40, 1.0 / 1e35, 1e-35 / 1e-36, 0.0 / 0.0, -1.0 / 0.0).
  • Validated emitted DXIL with dxil.dll and executed on D3D12 (NVIDIA GeForce RTX 5060 Ti).
  • cargo fmt -p victory-shader -- --check: passed.
  • cargo clippy -p victory-shader --all-targets -- -D warnings: passed (0 warnings).
  • cargo xtask policy: passed (asset policy: 151 files ok).
  • cargo test -p victory-shader: 70 passed, 0 failed.

@DaviTostes

Copy link
Copy Markdown

Tested 3e8f2d3 on Arch Linux x86_64, rustc 1.98.1: pass.

No game data used.

@r4tedx

r4tedx commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

A note from checking the open opcode PRs against AMD's ISA reference (I have #163 open, which leaves these three refused): as far as I can read this diff, v_div_scale_f32 takes src1 as the numerator and src2 as the denominator (let (a, num, den) = (f(self, 0)?, f(self, 1)?, f(self, 2)?), and the test program passes them that way too). The RDNA 2 ISA has them the other way round, opcode 365:

Single precision division pre-scale. S0 = Input to scale (either denominator or numerator), S1 = Denominator, S2 = Numerator. [...] S0 must be the same value as either S1 or S2.

and its pseudo-code starts

VCC = 0;
if (S2.f == 0 || S1.f == 0)
    D.f = NAN
else if (exponent(S2.f) - exponent(S1.f) >= 96)
    // N/D near MAX_FLOAT
    VCC = 1;
    if (S0.f == S1.f)
    ...

so a zero numerator or denominator gives NaN there. LLVM's LowerFDIV32 emits DIV_SCALE(RHS, RHS, LHS) for the denominator and DIV_SCALE(LHS, RHS, LHS) for the numerator, which matches (src1 = denominator, src2 = numerator). v_div_fixup_f32 is (quotient, denominator, numerator) in the same document.

If the roles are swapped in both the lowering and the test, the test would still pass while a real program's division scales the wrong way, so it may be worth a second look. I have not run this on hardware; this is from the documents only. No game data used.

@n-romanovich

Copy link
Copy Markdown
Author

Thanks for the review, @r4tedx!

Fixed in db20637:

  • Swapped v_div_scale_f32 operands to (src0, den, num) per RDNA2 ISA opcode 365 / LLVM LowerFDIV32, and returned qNaN (0x7FC0_0000) when either num or den is zero.
  • Updated valu_div_f32_sequence_executes_on_gpu to match the (den, num) operand order (keeping the original num in v1 for v_div_fixup_f32) and re-verified all 70 tests in victory-shader on D3D12 (RTX 5060 Ti).

AntoninMichelq pushed a commit to AntoninMichelq/VIctory that referenced this pull request Nov 24, 2026
… and v_div_fixup_f32) into the integration

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AZ9pSB4ZoXYUifuXg8gm66
muhammed-aksoy pushed a commit to muhammed-aksoy/VIctory that referenced this pull request Nov 24, 2026
@r4tedx

r4tedx commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

One more on this PR, for v_div_fmas_f32. The lowering scales by 2^64 or 2^-64 depending on the exponent of src2 (0x5F80_0000 / 0x1F80_0000). Both of AMD's references give a fixed factor:

  • RDNA 2 ISA, opcode 367: if (VCC[threadId]) D.f = 2**32 * (S0.f * S1.f + S2.f); else D.f = S0.f * S1.f + S2.f;
  • RDNA 3 ISA: if VCC.u64[laneId] then D0.f = 2.0F ** 32 * fma(S0.f, S1.f, S2.f)

(2^64 is the f64 form's factor.) A probe on an RTX 5070, with VCC set and inputs (1, 1, 0), returns 0x1F800000 (2^-64) where the reference gives 0x4F800000 (2^32).

For v_div_fixup_f32, the same document's case list has else if ((exponent(S2.f) - exponent(S1.f)) < -150) D.f = sign_out ? -underflow : underflow before the pass-through of the quotient; a probe with quotient 1, denominator 2^73, numerator 2^-126 returned 1 here.

From the documents and synthetic probes only; I have no copy of the title and have not run this on console hardware.

edsuuu referenced this pull request in edsuuu/VIctory-fork Nov 24, 2026
…iv_fixup_f32

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

upipibi commented Nov 24, 2026

Copy link
Copy Markdown

Review of 4c9a922 (read against the RDNA2 ISA, not run):

1. v_div_scale_f32's VCC depends on which operand S0 is (lower.rs:3744, flag_raw = select(is_den, uncancelled, up_raw)). In the RDNA2 ISA (§12.12, V_DIV_SCALE_F32, opcode 365), VCC is set only by the "exp(S2) − exp(S1) ≥ 96", "1/S1 and S2/S1 denormal" and "S2/S1 denormal" cases, all functions of S1 (denominator) and S2 (numerator). S0 only decides whether this instance's D is scaled, so both instances of one division agree on VCC. LLVM's f32 fdiv expansion feeds v_div_fmas_f32 the VCC of the numerator instance (v_div_scale_f32 vN, vcc, num, den, num). The GPU test reads the denominator instance's instead (mod.rs:610 / :622), which matches this lowering, so it passes. With LLVM's order:

  • 1.0 / 1e35: the ISA scales nothing (VCC = 0), giving 1e-35. Here den (biased exponent 243 ≥ 232) is scaled by 2^-64, num isn't, and the numerator instance's VCC is 0, so the quotient comes out about 1.84e-16.
  • -1.0 / 1e-40: the ISA's "≥ 96" case sets VCC = 1 for both instances, giving -inf. Here the numerator instance's VCC is num_tiny = 0, so the result is about -5.4e20.

Swapping vcc_lo and s16 in the test reproduces it. Suggestion: follow the ISA's case list for VCC and for the scale-both cases, and use S0 only to pick whether this instance's D is scaled.

2. v_div_fixup_f32 maps a NaN quotient to ±inf (lower.rs:3816, q_nan in make_inf). With finite, non-zero S1 / S2 the ISA returns sign_out ? -|S0| : |S0|, so fixup(NaN, 2.0, 1.0) should stay NaN; here it gives +inf.

Also: this inserts right above the v_fmac_f32 | v_mac_f32 | v_mac_legacy_f32 arm that #284 rewrites, so the two will conflict textually.

AI-assisted (Claude Code), read-only review.

@Lyrnc

Lyrnc commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

RDNA2 hardware probe of v_div_fixup_f32: two cases where the lowering here differs from the hardware. The rest of the special cases I tried agree.

Setup. AMD Radeon iGPU of a Ryzen 7 9800X3D, gfx1036 (RDNA2), AMD driver 32.0.21042.62, Windows 11 Pro 26200. A HIP kernel (assembled by the AMD driver's amd_comgr) runs v_div_fixup_f32 v10, v4, v5, v6 (quotient, denominator, numerator), compared with a Python transcription of this PR's v_div_fixup_f32 arm. Default mode (IEEE on, f32 denormals flushed). RDNA2 desktop silicon, not the console's. No game data.

quotient denominator numerator hardware this PR
0x7fc00000 (NaN) 0x3f800000 0x00000000 0x00000000 0x7f800000
0x7fc00000 0xbf800000 0x80000000 0x00000000 0x7f800000
0x7fc00000 0x7f800000 0x3f800000 0x00000000 0x7f800000
0x7fc00000 0xff800000 0x40400000 0x80000000 0xff800000
0x40000000 0x7149f2ca (1e30) 0x0da24260 (1e-30) 0x00000000 0x40000000
0x40000000 0x5d800000 (2^60) 0x12000000 (2^-91) 0x00000000 0x40000000
0x40000000 0x5d800000 (2^60) 0x12800000 (2^-90) 0x40000000 0x40000000
0x7fc00000 0x00000000 0x3f800000 0x7f800000 0x7f800000
0x7fc00000 0x3f800000 0x7f800000 0x7f800000 0x7f800000
0x7fc00000 0x3f800000 0x3f800000 0x7f800000 0x7f800000
  1. Order of the NaN-quotient case. q_nan joins make_inf, and make_inf is selected after make_zero. So a NaN quotient turns 0/x and x/inf into an infinity. On the hardware, 0/x and x/inf give a signed zero whatever the quotient is. The quotient's all-ones exponent only matters once the zero and infinity cases have passed: it gives ±inf, which you get right for finite non-zero operands (last row). Selecting q_nan before make_zero (or make_zero last) would match.
  2. The ISA's underflow step is missing. When the numerator's biased exponent minus the denominator's is below -150, the hardware returns a signed zero regardless of the quotient. With a 2^60 denominator, 2^-90 keeps the quotient and 2^-91 gives 0, so the threshold is exactly the ISA's < -150. The lowering returns the quotient there. In a full division sequence the quotient for such operands is probably already 0 under f32 flush, so this may not show up end to end. I only checked the fixup step.

The other cases match: 0/0 and inf/inf give 0xffc00000; a NaN numerator or denominator comes back quieted (0x7fa00000 → 0x7fe00000); x/0 and inf/x give a signed infinity. v_div_scale_f32 and v_div_fmas_f32 were not probed.

AI use: Claude Code (Claude Opus 5.5) wrote the probes, ran them on the GPU above and drafted this comment; the numbers come from the hardware run.

@upipibi

upipibi commented Nov 24, 2026

Copy link
Copy Markdown

Correction to point 2 of my review above, after @Lyrnc's RDNA2 probe: I said v_div_fixup_f32 should keep a NaN quotient as NaN when the operands are finite and non-zero. The hardware returns ±inf there (last row of their table: quotient NaN, 1.0 / 1.0 → 0x7f800000), which is what this PR does. So that part of the PR was right and my reading of the ISA was wrong. What the hardware does show is the order @Lyrnc describes: 0/x and x/inf give a signed zero whatever the quotient is, so make_zero has to win over the NaN-quotient case, plus the < -150 exponent-difference underflow step. Point 1 (v_div_scale_f32's VCC) is unaffected; it wasn't part of this probe.

AI-assisted (Claude Code).

@n-romanovich

Copy link
Copy Markdown
Author

Thanks for the review! Addressed the feedback and resolved the compilation issue in the latest commit. All tests pass cleanly.

@upipibi

upipibi commented Nov 24, 2026

Copy link
Copy Markdown

Checked 7706273: both points are addressed. VCC now comes only from the two operands' exponents (case_overflow | case_denorm), so both instances of one division agree. And v_div_fixup_f32 puts make_zero before the NaN quotient and adds the < -150 underflow, matching @Lyrnc's measurement.

One question, from reading the code (not run): the new v_div_scale_f32 scales only in those two cases. The ISA's other scaling rows (§12.12, opcode 365) are gone: S1 denormal → ldexp(S0, 64) for both instances; 1/S1 denormal → ldexp(S0, -64); and exp(S2) <= 23 → ldexp(S0, 64). With f32 denormals flushed on the host these may never change the final quotient, but a denormal denominator or a numerator near 2^-104 would be the inputs to check. Is dropping them intentional?

AI-assisted (Claude Code).

@DeerSilver

Copy link
Copy Markdown

Tested head 7706273 merged onto main ffe310e on NVIDIA GeForce RTX 5060 Laptop GPU (Blackwell), driver 621.24, Windows 11 26300, Rust 1.98.1. No game files: the test suite only.

Merged onto current main, the test build fails. 6638098 ("per-lane descriptors chosen by control flow", merged with #566 at 09:53) added a fourth argument to resource::track:

error[E0061]: this function takes 4 arguments but 3 arguments were supplied
  --> crates/victory-shader/src/emit/mod.rs (in the new test)
   |     resource::track(&p, &native.layout, native.stage)
   |     argument #4 of type `Option<&structure::Structured>` is missing

There's no text conflict, so GitHub still shows the PR as mergeable, but merging it as it is would break cargo test on main. The call this PR adds needs the fourth argument. main's own tests pass Some(&st); None keeps the old three-argument behaviour.

With , None added locally to that one call, everything passes:

  • The PR's GPU test ran on the RTX 5060 (DXGI adapter 0 on this laptop; no "no SM 6.6 device" skip) and passed:
    • valu_div_f32_sequence_executes_on_gpu
  • cargo test --workspace --locked: 343 passed, 0 failed, 6 ignored, against 342 passed / 6 ignored on main.
  • cargo clippy --workspace --all-targets --locked -- -D warnings: clean.

AI-assisted (Claude Code).

edsuuu referenced this pull request in edsuuu/VIctory-fork Nov 24, 2026
The tester tree (upstream main ffe310e plus its PRs, update 8; see its
INTEGRATION.md) ran 11-25 minutes in the world on an RTX 5070 without a
device removal. Where both sides carry the same PR (the wave64 stack
#223/#233/#320 with #439 and #180, #454, #336, #259, #331 and others), the
tester tree's newer head is taken; our own work and the PRs only we
merged are kept.

Conflicts, file by file:

- descriptor/host.rs: the tester layout (`spare`, the guard slot after the
  dynamic slots, `free_table`, the capped sampler heap). A capped view
  heap keeps `capped_reserve()` dynamic slots, now 2^18 by default (the
  tester measurement, and our 91fed158), still `VICTORY_DYNAMIC_SLOTS` in
  diagnostics builds; uncapped hosts keep our 2^19. Our slot statistics
  (TAKEN/PEAK/SHORT), the bindless plan cache (`CommittedRegions`,
  `timed_valid_title_address`, `timed_find`, `title_bounds`) and the
  revision triple are kept beside the tester's `guard_slot`.
- Buffer states: the tester tree's buffer-state tracker (#334: every list
  moves host copies of title memory between GENERIC_READ and
  UNORDERED_ACCESS and back to common before it closes) and depth twins
  (#469) are taken. #40's enhanced/legacy indirect barriers (the indirect
  prelude, `use_indirect_buffers`, the title buffer handoff mirrored in
  `host_barrier`) cannot share buffers with that tracker and are dropped;
  #40's argument checks (`byte_len`, exact spans, overflow-safe clamp
  shader, aligned counts) stay. `indirect::bound` and #282's
  `rectangles` go through `buffer_state`, and `indirect::execute` (#334)
  replaces `done`. #178's DXC fallback compiles both of our passes.
  Our segments (#387: `close` ends the segment, `close_native` closes a
  native list) carry the tracker: each native list returns its buffers
  to common and its twins to their depth targets, and each prelude also
  holds our texture uploads.
- shadow.rs: our write flow (`queue_write`, one `snapshot` after the
  batch's refreshes, `finish_writes`, the unchanged-page cache) with
  #261's copy-back that also gives the snapshot the title's bytes; its
  tests run through our flow.
- pipeline/make.rs: #275's per-frame budget and per-pipeline wake pair,
  with our compute waits (a dispatch waits for its pipeline, up to 20 s).
- pipeline/library.rs: the tester version (#347, #275's saver thread);
  our concurrent-write test kept. shader_cache.rs: our byte-returning
  cache API with #358's "translated, only not kept".
- draw.rs: #493's root SRV tables; where no table can stand in, our
  drop of a draw whose root view is unset or outside title buffers. Our
  refusal of a table offset past the capped heap stays.
- resource.rs: `HostTexture` has both our `staged` generation and the
  depth twin.
- Shaders: the tester's lower.rs for the wave64 stack, #160's image
  sampling (it covers our #73 and #136 sample forms) and #453/#587; kept
  from our side: #136's preference for an image or buffer use of a
  descriptor read as data and its `s_buffer_` arm, #422's nearest-even
  narrowing (also for #169's d16 loads and #453's interpolation), #452's
  spin-wait limit, #391's LDS limit, #302's spilled root arguments (now in
  `NativeProgram::translation_ir`), #136's PSV0 interpolation beside the
  tester's row harmonisation. split_tests.rs, lane_read_loop_tests.rs and
  docs/wave64-on-wave32.md are the tester versions (the same PRs at newer
  heads).
- Tests: #483's heap guard dwords filled in our GPU tests of #200
  (v_div_scale) and #437 (scalar loads from a raw view), which read
  through the guard slot otherwise; #334's debug-layer test passes an
  offset to our `indirect::bound`.

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

Copy link
Copy Markdown

Merged onto main @ ffe310eb, this PR (77062732) no longer compiles its tests. crates/victory-shader/src/emit/mod.rs:833 calls resource::track with 3 arguments. Since 6638098 it takes a 4th, lanes: Option<&Structured>; main's tests pass Some(&st) with let st = structure::structure(&p).unwrap();.

Checked with CI's steps (both clippy runs with -D warnings, cargo test --workspace) on Windows 11, AMD RX 9070. Every open PR: https://gist.github.com/alexdeliu/ef9ef0ebc1776ff104b5aa8eaea18e87

@n-romanovich

Copy link
Copy Markdown
Author

Thanks for testing and pointing this out, @alexdeliu!

Merged latest main and updated resource::track in the test to pass Some(&st) per 6638098. Verified with cargo clippy --all-targets --locked -- -D warnings and re-ran the GPU test — both compile cleanly and pass with 0 warnings.

@alexdeliu

Copy link
Copy Markdown

@n-romanovich rechecked 93f052e2 merged onto main @ ffe310eb on the RX 9070: both CI clippy runs are clean and cargo test --workspace passes (343 tests).

Copy link
Copy Markdown
Owner

Automated triage for the maintainers.

Needs work. The operand order, VCC from the S1/S2 exponents, the 2^32 factor in v_div_fmas_f32, and the zero-before-NaN order and < -150 underflow in v_div_fixup_f32 now follow the RDNA2 ISA and the hardware probes posted here.

v_div_scale_f32 in crates/victory-shader/src/emit/lower.rs still implements only two rows of the ISA's case list: exp(S2) - exp(S1) >= 96 and S2/S1 denormal. Missing: S1 denormal (ldexp(S0, 64)); 1/S1 denormal (ldexp(S0, -64)); 1/S1 and S2/S1 both denormal; exp(S2) <= 23 (ldexp(S0, 64)). These matter in the console's mode, where 32-bit denormals are flushed: for a denominator above 2^126 (e.g. 1e30 / 1e38), v_rcp_f32 of the unscaled denominator flushes to 0 and the sequence returns 0 instead of about 1e-8.

What would change the verdict: implement the remaining rows (or show why each cannot affect the result) and add test lanes for a denominator above 2^126, a denormal denominator and a numerator with exponent <= 23.

Not a duplicate of #166: that PR lowers different opcodes. CI: no check runs on the head commit.


Generated by Claude Code

@n-romanovich

n-romanovich commented Nov 25, 2026 •

Copy link
Copy Markdown
Author

@Marvisak, thanks for the review.

In 8201c0e, I implemented the remaining v_div_scale_f32 cases in crates/victory-shader/src/emit/lower.rs:

  • S1 denormal (ldexp(S0, 64) for both operands, VCC = 0), using normal-float scaling (2^-62 + mant * 2^-85) - 2^-62 when !case_overflow so FTZ does not flush denormal inputs to 0.
  • 1/S1 and S2/S1 both denormal (S1 * 2^-64, S2 * 2^64, VCC = 1).
  • 1/S1 denormal (|S1| > 2^126: ldexp(S0, -64) for both operands, VCC = 0).
  • exp(S2) <= 23 (ldexp(S0, 64) for both operands, VCC = 0).

Added the requested GPU test lanes in crates/victory-shader/src/emit/mod.rs (1e30 / 1e38, 1e-40 / 2e-40, and 2e-34 / 4.0) and re-ran cargo test -p victory-shader --locked -- valu_div_f32_sequence_executes_on_gpu on Windows 11 (NVIDIA GeForce RTX 5060 Ti): 1 passed, 0 failed.

On CI, valu_div_f32_sequence_executes_on_gpu passes; the two failures in emit::synthetic_tests (gathers_at_a_level_match_the_hardware and permutes_read_the_lane_named_and_zero_from_lanes_left_out) are pre-existing main failures on the WARP runner (no hardware GPU / wave-32 support).

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.

8 participants