Skip to content

Translator: MODE f16/f64 rounding from s_setreg FP_ROUND[3:2] (SHADER-35) - #753

Merged
ItsNotRexed merged 8 commits into
ItsNotRexed:mainfrom
Pipodi:shader35-mode-round
Nov 22, 2026
Merged

ItsNotRexed merged 8 commits into
ItsNotRexed:mainfrom
Pipodi:shader35-mode-round

Conversation

@Pipodi

@Pipodi Pipodi commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Claimed in the coordination issue as: SHADER-35 (claimed in #156, carried over to #374, #634, #1006 and #1218)

Depends on: none (built on #575 and #394, both merged)

What and why

The game changes the MODE register's f16/f64 rounding field from inside its shaders, and the translator ignored that. The corpus count (disassembly, counts only):

  • The only MODE field written is FP_ROUND[3:2], via s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2). There are 9,417 writes in 6,333 shaders: 6,694 set toward zero (3) and 2,723 set nearest even (0).
  • Most writes come partway through a program, and 4,317 toward-zero windows stay open until s_endpgm.
  • There are no s_denorm_mode or s_round_mode instructions. The s_setreg_b32 writes in the corpus target HW_REG_POPS_PACKER, not MODE.
  • The f16-result ops inside toward-zero windows are mostly v_interp_p2_f16 (59k in program order). v_fma_mix_f32 (211k) has an f32 result and is not affected. v_cvt_f32_f16 is exact. pkrtz already rounds toward zero.

What this PR changes:

  • Mode tracking. When a program writes the field, the translator keeps it in a per-invocation Function variable.

  • f16 results. Every VALU f16 result goes through one new helper, f16_res. It uses Translator: f16 rounding — integer f16 narrowing and single-rounded f16 FMAs (SHADER-55, SHADER-56) #575's integer f16_bits, or f16_bits(rtz=True) (the conversion v_cvt_pkrtz_f16_f32 uses) while the mode is toward zero.

    • The paths covered are f16_out (f16 arithmetic), v_pk_*_f16 through f16_pack2, v_cvt_f16_f32, v_interp_p2_f16 and v_fma_mix{lo,hi}_f16.
    • v_rcp/rsq/sqrt/sin_f16 ignore MODE on hardware (RX 6800, @shelbykb2), so they keep nearest even. v_cos/exp/log_f16 do the same; those three are unmeasured and assumed to match.
    • Both forms use integer ops only, so there is no PackHalf2x16 and no round trip a driver can fold.
    • Toward zero, finite overflow gives ±65504, inf stays inf, and f16 subnormals are kept.
  • Exact toward zero. f32 rounding followed by f16 truncation alone is not exact.

    • Example: 2 − 2⁻²⁴ is an f32 tie that rounds up to 2.0, while toward zero it is 0x3FFF.
    • So f16 add and sub, and v_pk_add_f16, step the f32 sum one ulp toward zero when its exact TwoSum error shows it rounded away from zero.
    • f16 FMAs need nothing extra. The round-to-odd f32 value from Translator: f16 rounding — integer f16 narrowing and single-rounded f16 FMAs (SHADER-55, SHADER-56) #575's fma_f16_odd narrows exactly in either direction.
    • v_fma_mix{lo,hi}_f16 toward zero round once, as measured: the f32 Fma is corrected to round-to-odd from the exact residual, then truncated. Two edge cases are handled: products below 2^-64, where the f32 error term can't be held, use the product's sign, and an f32 overflow with finite inputs gives ±65504. Nearest-mode mix still rounds twice, as on main (unmeasured).
  • f64. v_add_f64 is the only f64 op with an f64 result in these shaders. When the exact TwoSum error shows the nearest result rounded away from zero, it steps one ulp toward zero. Every float op is already NoContraction, which keeps TwoSum exact. The step works on the raw sum, and clamp/omod apply after it, as on the hardware.

  • Unchanged shaders. Shaders that never write MODE emit the same SPIR-V as main. The corpus check below finds byte-identical .spv for every one of them.

  • Refused instead of skipped. These now raise Unsupported:

    • MODE writes to other bits (f32 rounding, denormals);
    • partial field writes;
    • directed rounding (+inf/−inf);
    • register-valued writes;
    • s_denorm_mode and s_round_mode.

    None of these occur in the corpus.

  • Not covered. Memory and texture format conversions (d16 results included) don't follow MODE and are unchanged. Denormal handling is still Vulkan's default.

  • Known edge, from main. On the RX 6800, omod (mul:2/mul:4/div:2) is ignored while denormals are kept and applied when they are flushed. The translator applies it in both cases, as main does. This PR doesn't model that, and it no longer tests an omod order (noted in design.md).

docs/design.md describes this in Known approximations, and the f16 rounding row points there. tests/test_mode_round.py covers:

  • toward zero, back to nearest, and no write;
  • negative values, overflow and saturation, inf, f16 subnormals and underflow;
  • both halves of v_pk_add_f16 and v_pk_fma_f16;
  • the 2 − 2⁻²⁴ cases for add, sub, fma and an op_sel high destination;
  • v_add_f64 (1 − 2⁻⁶⁰, overflow);
  • @shelbykb2's RX 6800 words: 2 + 2^-24, −1 − (2^-11 + 2^-21), 65504 + 16, the transcendentals in every mode, and fma_mix (1×2 − 2^-30 gives 3fff), plus the tiny-product and overflow cases;
  • the refused writes.

tests/spirv_interp.py gains binary64 arithmetic and double/v2uint bitcasts so those tests can run.

Tested

On 4f7aeb8 (main 426023a merged), Windows 11, LLVM 23.1.5 (I didn't run it on a GPU; the GPU results are from others, below):

  • python -m pytest tests/: 4,193 passed, 57 skipped. python -m unittest discover -s tests/semantic: 1,139 OK.
  • Full corpus (26,503 shaders, tools/rdna2spirv.py --no-asm sharded), main 426023a vs this branch:
    • main 426023a: 26,503 translated, 26,503 pass spirv-val
    • branch 4f7aeb8: 26,503 translated, 26,503 pass spirv-val
    • lost 0, gained 0; wave64 shaders 21,554 on both, no flips
    • .spv bytes: 20,170 identical; 6,333 changed, every one a shader that writes MODE; 0 changed without a MODE write
  • Others' runs (thanks): @dougmb (RTX 3060, Linux) and @Proudnoob4 (a second game copy) found the same 6,333 = MODE-writer set. @kotorvr's 4090 run passes. @shelbykb2 measured the rounding on an RX 6800 (gfx1030), and the fixes above follow that measurement. @Vonsek ran in-shader 0→3→0 MODE transitions in a pixel shader on an RTX 5080 and an AMD GPU, and all 4,096 pixels match bit for bit.

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.

AI-assisted: yes. Written with Claude Code; I reviewed the change and ran the tests and corpus check above.

🤖 Generated with Claude Code

Pipodi and others added 2 commits November 22, 2026 03:11
The game sets MODE.FP_ROUND[3:2] (f16/f64 rounding) inside its shaders: 9,417 writes in 6,333 of 26,503
shaders, 6,694 toward zero (3) and 2,723 back to nearest even (0); no other MODE field, no s_denorm_mode or
s_round_mode. The translator ignored it.

- The field is kept in a per-invocation Function variable (%mode_r16) when the program writes it.
- Every VALU f16 result (f16_out, v_pk_*_f16 via f16_pack2, v_cvt_f16_f32, v_sin/cos_f16, v_interp_p2_f16,
  v_fma_mix{lo,hi}_f16) goes through f16_res: main's integer f16_bits, or f16_bits(rtz=True) while the mode
  is toward zero. Integer ops only either way (SHADER-56).
- f16 add/sub and v_pk_add_f16 step the f32 sum one ulp toward zero when its exact TwoSum error shows it
  rounded away from zero (2 - 2^-24 is an f32 tie that rounds to 2.0; toward zero it is 0x3FFF). f16 FMAs
  need nothing extra: fma_f16_odd's round-to-odd f32 value (SHADER-55) narrows exactly in either direction.
- v_add_f64 steps one ulp toward zero the same way (finite overflow -> +-DBL_MAX), on the raw sum, before
  clamp/omod.
- Other MODE writes (other bits, partial field, +inf/-inf, register values), s_denorm_mode and s_round_mode
  raise Unsupported; none occur in the corpus.
- Shaders that never write MODE emit the same code.

tests/test_mode_round.py; tests/spirv_interp.py gains binary64 arithmetic, double <-> v2uint bitcasts and
vector Fma/FMin/FMax/FClamp. docs/design.md: Known approximations and the f16 rounding row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ention MODE

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

dougmb commented Nov 22, 2026

Copy link
Copy Markdown

Tested 2d47ebc merged into main 67204bf (the merge was clean then; the PR now conflicts with main 8df277f after the last merge round) on an NVIDIA RTX 3060, driver 620.73.04, Linux, with my own copy of the game (package 1.0.2.1): pass.

Full corpus, rdna2spirv.py --wave64-emulate in 16 shards over the same disassembly (gfx1013), compared with main 67204bf:

main 67204bf this PR
translated 26,503 / 26,503 26,503 / 26,503
pass spirv-val 26,503 26,503
  • .spv byte-identical to main: 20,170; different: 6,333; none missing on either side.
  • The 6,333 that differ are exactly the set of shaders whose disassembly contains hwreg(HW_REG_MODE (compared by name, set-equal). That confirms the PR's claim that shaders which never write MODE emit the same SPIR-V as main.
  • Independent count of the writes: 9,417 × s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2) in 6,333 shaders, and no s_denorm_mode / s_round_mode, matching the PR body.
  • scripts/run_gpu_tests.py: 64/91 passed, 27 skipped (wave64 only; this GPU has 32-wide subgroups), 0 failed, the same as main.
  • python -m unittest discover -s tests/semantic: 924 tests OK.

Not covered: the PR adds no GPU fixture for the toward-zero f16/f64 paths, so this shows that nothing regresses and that the change is confined to the MODE writers, not that the rounding matches the hardware. Counts only; no shader names or game data posted.

AI-assisted (Claude Code).

fearkov added a commit to fearkov/Leonida that referenced this pull request Nov 22, 2026
f16_pack2 packs VALU results, and MODE.FP_ROUND will change how it rounds (ItsNotRexed#753). A d16 buffer load is converted outside the VALU, like a d16 image result, so it takes the memory packer.
@shelbykb2

Copy link
Copy Markdown
Contributor

RDNA2 hardware measurement for this PR, as @dougmb's review asked for: f16 and f64 VALU ops run as raw compute kernels on an AMD Radeon RX 6800 (gfx1030, not the console's gfx1013; the hw-oracle tool from the AnyPS5 project) under each rounding mode, wave32 and wave64 (identical words). The mode was set for the whole kernel through the kernel's MODE word, which I assume behaves like a shader's own s_setreg write; that equivalence was not tested. I read this PR's code and ran its test's input words on hardware; I did not run the branch.

Your toward-zero results match hardware on the paths this PR changes. Every toward-zero word your test expects for v_add/sub/mul/fma_f16, the packed forms, v_cvt_f16_f32 and v_add_f64 (without an output modifier) equals the hardware word, including 2 − 2^-24, max + max and the cvt cases.

Which rounding field an op follows (0 nearest even, 1 +inf, 2 −inf, 3 zero):

Op Follows
v_add/sub/mul/fma_f16, v_pk_add/mul/fma_f16, v_cvt_f16_f32 the f16/f64 field
v_fma_mixlo/hi_f16 the f16/f64 field, with ONE rounding of the exact fma
v_add_f64, v_mul_f64 the f16/f64 field
v_cvt_f32_f64, v_fma_mix_f32, f32 ops the f32 field
v_rcp_f16, v_sqrt_f16, v_rsq_f16, v_sin_f16 neither: the same words in every mode
v_cvt_pkrtz_f16_f32 neither: always toward zero

Deciding rows (f16 result; nearest / +inf / −inf / zero): 2 + (−2^-24): 4000 / 4000 / 3fff / 3fff. 2 + 2^-24: 4000 / 4001 / 4000 / 4000. −1 − (2^-11 + 2^-21): bc01 / bc00 / bc01 / bc00. 65504 + 16: 7c00 / 7c00 / 7bff / 7bff. 1 + (−1): 0000, except 8000 under −inf. Under toward zero a finite overflow saturates (7bff, f64 7fefffff:ffffffff); nearest gives inf.

Where the PR, as I read it, differs from hardware

  1. v_rcp/sqrt/rsq/sin_f16: the PR makes them follow toward zero; hardware ignores the mode for these.
  2. v_fma_mixlo/hi_f16: rounded to f32 first and then narrowed (main does the same). Toward zero, 1×2 − 2^-30 is 3fff on hardware and 4000 that way.
  3. Output modifiers, and test_add_f64_mode_rounds_before_omod: see below. On hardware v_add_f64 (1 − 2^-60) mul:2 gave 3ff00000:00000000 (nearest) and 3fefffff:ffffffff (toward zero), unscaled, where the test expects 40000000:00000000 / 3fffffff:ffffffff.
  4. A test-syntax note: v_add_f16_e64 … op_sel:[0,0,1] does not assemble for gfx1030 or gfx1013 with llvm-mc 21; I measured that case with v_fma_f16 … op_sel:[0,0,0,1].

Output modifiers depend on the denormal mode. All the runs above kept denormals (the MODE denormal fields = 3), and there mul:2, mul:4 and div:2 did nothing, on f16, f64 and f32 ops alike. I then ran the same instructions with denormals flushed (field = 0), and the modifiers were applied:

Instruction (inputs) Denormals kept Denormals flushed
v_mul_f32 1.0, 1.0 mul:2 3f800000 (1.0) 40000000 (2.0)
v_mul_f32 3.0, 0.5 mul:4 3fc00000 (1.5) 40c00000 (6.0)
v_mul_f32 3.0, 0.5 div:2 3fc00000 (1.5) 3f400000 (0.75)
v_med3_f32 1.0, 1.0, 2.0 mul:2 3f800000 (1.0) 40000000 (2.0)
v_mul_f16 1.0, 1.0 mul:2 3c00 4000
v_fma_f16 … div:2 (result 1.0) 3c00 3800

That agrees with LLVM's SIFoldOperands ("if output denormals are enabled, omod is ignored"). The translator applies output modifiers unconditionally and does not read the denormal mode, so which side is right for the game depends on the mode its shaders run in. Because of this I could not measure whether the modifier comes before or after rounding with denormals kept; that needs runs with denormals flushed and a non-default rounding mode, which I have not done.

Also seen, not specific to this PR: v_cvt_f16_f32_e64 … clamp clamps on hardware; main and this PR ignore the clamp there.

Not measured: v_interp_p2_f16 (pixel-shader only; most of the game's affected instructions), gfx1013 itself, NaN operands, IEEE mode on, modes 1 and 2 against this PR (it rejects them).

49 dispatches, 0.8 to 3.1 s each. AI-assisted (Claude Code).

@kotorvr

kotorvr commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Tested 2d47ebc on RTX 4090 (driver 621.14, 32-wide subgroups), Windows 11 26200: pass

  • RelWithDebInfo Ninja build of runtime/ (MSVC, Vulkan SDK 1.4.363.0); ctest: 28/28
  • python -I scripts/run_gpu_tests.py: 64/91 passed, 27 skipped (wave64 tests skip without emulation); with LEONIDA_W64_EMULATE=1: 91/91 passed. main 4a36bb1 on the same machine: 73/100 passed, 27 skipped and 100/100 passed
  • python -m unittest discover -s tests/semantic: 898 OK (main: 1016)
  • python -m pytest tests --ignore=tests/semantic: 2104 passed, 3 skipped, 1 xfailed (main: 2314 passed, 9 skipped, 1 xfailed)

The totals are below main's because this branch is 397 commits behind main 4a36bb1, so it lacks the tests added since then. Nothing failed or regressed.

No game files used. AI-assisted run (Claude Code).

@Proudnoob4

Copy link
Copy Markdown
Contributor

Game-copy check of 2d47ebc (this PR's head as it stands; it conflicts with main) on my own Xbox Series 1.0.2.1 copy. Disassembly from make_game.py at 91b36cf (gfx1013), Windows 10, RTX 4080.

Corpus counts: your numbers match exactly on a second copy.

  • s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2): 9,417 writes in 6,333 shaders, and no other MODE field is written.
  • 6,694 set toward zero (3) and 2,723 set nearest even (0).
  • 4,317 toward-zero windows are still open at s_endpgm (counted in program order).
  • 0 s_setreg_b32 to MODE, 0 s_denorm_mode, 0 s_round_mode.

Whole corpus, translated with --wave64-emulate (14 shards), this PR against its merge base 762893f:

merge base this PR
translated / pass spirv-val 26503 / 26503 26503 / 26503
  • 6,333 modules change, and they are exactly the 6,333 shaders that write FP_ROUND (the sets match name for name).
  • The other 20,170 are byte-identical. No module that lacks a MODE write changes, and every one that has one does.

Tests on this head: tests/test_mode_round.py 28 passed (pytest); tests/semantic 898 OK. Not run on a GPU here.

Counts only; no shader data. AI-assisted (Claude Code in OpenCode): it ran these on this machine.

Pipodi and others added 2 commits November 22, 2026 09:05
Conflicts in tools/rdna2spirv.py (f16_out keeps main's fract flag and narrows with f16_res; v_interp_p2_f16 keeps main's clamp and narrows with f16_res; v_fma_mix goes through main's f16_out) and docs/design.md (main's new rows kept, our f16 rounding and Known approximations rows kept).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
rcp/rsq/sqrt/sin/cos f16 ignore the rounding mode (always nearest even); v_fma_mix{lo,hi}_f16 toward zero rounds the exact fma once (round-to-odd f32 from the product/sum residual, then truncate); the v_add_f64 omod test no longer claims an omod order (omod vs denormal mode is unmodelled, noted in design.md). Tests with the measured words.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Pipodi and others added 4 commits November 22, 2026 09:37
fma_mix_odd: a tiny product takes the residual sign from its operands (independent of denormal flushing), an f32 overflow with finite operands gives +-FLT_MAX toward zero. v_exp_f16 and v_log_f16 narrow to nearest even like the measured transcendentals (cos too; all three unmeasured). Docs and test comments corrected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The ten tests/semantic/fixtures/disasm/*.s files main added (4030a38, 87d7bf7, 1293cc2, 1b6cc3f, ad6bb01,
5c74ec3) were left out of the merge commit; they are restored byte-identical to d3841c0.

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

Vonsek commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

I tested the in-shader MODE transitions on 2d47ebc47341d0d3a4aeff5b6a7091dbb21c6f5c in a translated pixel shader. Each invocation converts the same f32 three times with v_cvt_f16_f32, writing hwreg(HW_REG_MODE,2,2) to 0, 3 and 0 before the respective conversions. R, G and B export the numeric half-word values (exact integers in RGBA32F). The full-screen triangle's four quadrants select the exact halfway magnitudes 1 + 3·2^-11 or 1 + 2^-11 and either sign.

On Windows RTX 5080 and AMD Radeon Graphics all 4,096 pixels agreed with the bit-level CPU expectation, including the restored nearest-even result in B. For the first magnitude the positive quadrant returned half words 3c02/3c01/3c02, the negative quadrant bc02/bc01/bc02; for the second magnitude all three results were 3c00 or bc00. Changing only the middle mode write from 3 to 0 changed exactly 2,048 green-channel values per GPU and left all other channels identical. All modules passed spirv-val and the draws produced no validation VUID. This complements the earlier fixed-MODE raw-hardware measurements. Source-built fixtures; AI-assisted.

I have now checked the in-kernel writes on physical RDNA2 gfx1036 (AMD Radeon Graphics, Windows driver 32.0.21045.16010) as well. I assembled raw kernels with the #1248 oracle, seeded each destination VGPR to zero, wrote hwreg(HW_REG_MODE,2,2) before each conversion, and read back the entire MODE word after each write. The two initial modes 0x1c0 and 0x3c0 changed to 0x1cc and 0x3cc for RTZ and returned to their respective initial value. Across wave32/wave64, both initial modes, four signed halfway inputs and a middle-write-0 control, 32/32 kernels matched all eight expected output words (three converted values, unchanged input, and four MODE reads). The low half words exactly match the translated pixel results above.

@Pipodi

Pipodi commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @dougmb, @kotorvr, @Proudnoob4 and @Vonsek for the runs, and @shelbykb2 for the RX 6800 measurements. They changed the PR (4f7aeb8, merged with main 426023a):

  • v_rcp/sqrt/rsq/sin_f16 ignore MODE again, as measured. v_cos/exp/log_f16 do too; they weren't measured, so that's assumed from the others and documented.
  • v_fma_mixlo/hi_f16 toward zero round once. The f32 Fma is corrected to round-to-odd using the exact residual, then truncated to f16. Your 1×2 − 2^-30 case gives 3fff, and nearest still gives 4000. Two edges are handled: products below 2^-64 use the product's sign, and an f32 overflow with finite inputs gives ±7bff. Nearest-mode mix still rounds twice, as on main; that's unmeasured and outside this PR.
  • Output modifiers: test_add_f64_mode_rounds_before_omod expected an order your runs show doesn't exist while denormals are kept, so it is replaced by a toward-zero test without omod. design.md now says that omod vs. the denormal mode is unmodelled (ignored when kept, applied when flushed, as measured). The translator still applies omod in both cases, as main does.
  • Your words are tests now (tests/test_mode_round.py, 53 tests).
  • The merge with main keeps the MODE rounding on Translator: read the high f16 half in v_interp_p1ll_f16 / v_interp_p2_f16 (high) #1214's new v_interp_p2_f16 high path.

Not changed here: the v_cvt_f16_f32 clamp (also on main) and the omod/denormal dependency. Both are worth their own items.

Corpus, main 426023a vs this branch: 26,503/26,503 translated and valid on both, 0 lost. 20,170 .spv are byte-identical, and the 6,333 that changed are exactly the MODE writers. The PR body's Tested section has the details.

Counts only, no game files. AI-assisted (Claude Code).

@ItsNotRexed
ItsNotRexed merged commit b409323 into ItsNotRexed:main Nov 22, 2026
ItsNotRexed pushed a commit that referenced this pull request Nov 22, 2026
…e kept

The conflict resolution in b409323 kept both versions of the row: the one from #753 and main's older one,
which still says the MODE register is ignored. The old row's other content (pkrtz, v_mul_legacy_f32) is in
the #753 row word for word, so only the contradiction goes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.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.

7 participants