Skip to content

Translator: smaller f16 narrowing, same bits (SHADER-489) - #2731

Closed
tibzejoker wants to merge 1 commit into
ItsNotRexed:mainfrom
tibzejoker:translator/f16-narrowing-size
Closed

tibzejoker wants to merge 1 commit into
ItsNotRexed:mainfrom
tibzejoker:translator/f16-narrowing-size

Conversation

@tibzejoker

@tibzejoker tibzejoker commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Claimed in the coordination issue as: SHADER-489 (claim, carried over to #2716)

What and why

Gen.f16_bits narrows with integer ops on purpose (#513, SHADER-56). This keeps that, and leaves out two steps that can't change the result:

  1. In nearest-even mode, the infinity select. Infinity is already above the overflow threshold, which gives 0x7C00.
  2. For v_add_f16, v_sub_f16, v_subrev_f16 and v_pk_add_f16 without omod, the subnormal rounding and the underflow select. A sum of two f16 values is a multiple of 2^-24, so below 2^-14 it already is an f16 value. Clamp keeps that true. An omod doesn't (div:2 can create a tie), so those keep the rounding.

SPIR-V instructions added per RDNA instruction (hand-written compute probes with inputs loaded from a buffer, 40 copies minus 8, on 49475796):

Instruction raw before raw after spirv-opt -O before after
v_add_f16, v_sub_f16 65 49 47 31
v_add_f16 clamp 66 50 48 32
v_add_f16 div:2 67 65 48 46
v_pk_add_f16 107 75 90 58
v_mul_f16 65 63 47 45
v_fma_f16 92 90 66 64
v_add_f16, shader writes MODE 114 96 n/a n/a

The last row has no optimized count because the probe writes a constant MODE, which the optimizer folds.

Tested

Windows 11, CPU only.

  • Exhaustive equivalence: the integer sequences emitted before and after were turned into C and run on all 2^32 f32 inputs (both roundings) and all 2^32 f16 operand pairs (both roundings, with and without clamp): 0 differences. The nearest-even result also equals x86 F16C on both domains. Negative control: applying the shortcut to div:2 gives 4,196,352 mismatches.
  • python -m unittest discover -s tests/semantic on ec8ec4c9 + this commit: 4,142 pass, including 5 new tests. The new omod test fails if the shortcut is applied with an omod.
  • The f16, MODE, d16, FMA, translate, line-ending and docs test files under pytest: 343 passed, 555 skipped (including tests that need an amdgcn llvm-mc, which this machine lacks), 0 failed, same as untouched ec8ec4c9.
  • The probe modules above pass spirv-val.

Rebased on ec8ec4c9 (only docs/design.md conflicted): the exhaustive check and the table above were rerun there, with the same results.

Not run by me: any GPU test, the game's shader corpus (so no before/after translated and valid counts), and driver ISA statistics. duudiis posted an independent RTX 5070 check of the same change (on the pre-rebase head) in the comments.

Overlap: #1970 and #1281 touch neighbouring lines. I'll rebase if either lands first.

AI-assisted (Claude Code).

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.

🤖 Generated with Claude Code

@duudiis

duudiis commented Nov 22, 2026

Copy link
Copy Markdown

Independent RTX 5070 Vulkan check at 6d599921 against parent 49475796 (Windows, driver 621.24, subgroup size 32).

  • 9,474,864 output words matched the parent bit for bit across native wave32 and emulated wave64, with both default rounding and explicit MODE RNE/RTZ. The eight forms covered scalar add/sub/subrev, scalar clamp and half selection, scalar div:2, packed add, and packed add with lane selectors and clamp. Each configuration used 197,393 dynamic input rows, pairing every half encoding with cancellation, adjacent encodings, and deterministic scrambled operands, plus a Cartesian matrix of edge values. Observed the expected (1 + 2) * 2^-25 control round to half bits 0x0002 in RNE and 0x0001 in RTZ. Scalar writes preserved the untouched half.
  • 1,142,868 conversion results matched an independent binary16 reference across both wave settings. The inputs straddled every signed half rounding midpoint and included overflow, infinity, signed zero, and NaN payloads. This also covers the RNE infinity-select removal outside the sum path.
  • All modules passed Vulkan 1.2 SPIR-V validation. In the default-rounding wave32 probe, optimized module size fell from 16,484 to 13,452 bytes with spirv-opt -O. The five new CPU semantic tests passed.

Used synthetic listings via the semantic translator and executed them through a Vulkan compute harness. The LLVM-backed valu_fuzz.py and original AMD hardware were outside this check.

@ricarmandoagent

Copy link
Copy Markdown

Reviewed 6d59992116dc25f74ba1fe1f7847031c19727633, base origin/main 49475796c226c8511b9470bf97a4daf57b8af323. Bazzite Linux, Python 3.15.2, x86-64 (16 threads), CPU only.

Repo checks (worktree /home/armand/src/leonida-rev11-2731):

  • python3 -m compileall -q make_game.py tools tests clean; python3 -I make_game.py --help OK.
  • python3 -m unittest test_f16_sum_narrowing -v -> 5 tests OK.
  • python3 -m unittest discover -s tests/semantic -> Ran 2572 tests ... OK (148.8 s), the same count as the description.
  • python3 -I tests/test_docs_design_rows.py -> 3 failures on this head and the same 3 on origin/main (docs/testing.md duplicate rows), so not from this PR.

Is the new test vacuous? It passes unchanged against the origin/main translator (LEONIDA_TOOLS_DIR=/home/armand/src/leonida-rev11-main/tools): as expected for an equivalence/regression test, it does not discriminate old from new. The negative control has teeth: with the omod exclusion removed (exact = k in ("OpFAdd", "OpFSub"), the shortcut also under div:2) in a copy of tools/, test_omod_result_is_still_rounded fails with AssertionError: 1 not found in (2, 3). The add/sub/pk_add tests stay green under that mutation, which is consistent: a sum of f16 operands is exact below 2^-14 whatever the omod.

Independent re-derivation of "same bits" (CPU). I transcribed Gen.f16_bits from the two versions myself and first cross-checked the transcription against the translated SPIR-V through spirv_mini_interp: 276 arbitrary f32 through v_cvt_f16_f32, 276 through v_cvt_pkrtz_f16_f32 (rtz), 656 f16 pairs through v_add_f16 -> 0 mismatches; then the C model against the Python one on 20,000 inputs -> 0 mismatches. Exhaustive (C, OpenMP, 12 s):

  • all 2^32 f32 inputs, f16_bits without the shortcut, head vs main: nearest 0 diffs, rtz 0 diffs;
  • head nearest vs x86 F16C _cvtss_sh, all 2^32 f32: 0 diffs;
  • all 2^32 f16 operand pairs through v_add_f16, shortcut vs main: nearest 0, rtz 0, clamp 0, clamp+rtz 0;
  • negative control, the same shortcut applied to v_pk_mul_f16's product: 246,418,844 diffs of 4,294,967,296.
    So the infinity-select removal and the exact_tiny narrowing are equivalent on exactly the domains claimed, and the check does catch the shortcut outside them.

Instruction counts (40 copies minus the 0-copy baseline, asm lines from tools/rdna2spirv.py, main -> head): v_add_f16 66.83 -> 50.80 (-16.03), v_add_f16 clamp 67.83 -> 51.80 (-16.03), v_add_f16 div:2 69.85 -> 67.85 (-2.00), v_pk_add_f16 108.80 -> 76.78 (-32.02), v_mul_f16 66.83 -> 64.83 (-2.00). The deltas match the table (65->49, 66->50, 67->65, 107->75, 65->63); my absolute values are ~1.8/instruction higher because the probe also counts the per-instruction register bookkeeping. spirv-as + spirv-val --target-env vulkan1.2 accept a 40x v_add_f16 probe. The spirv-opt row is not re-derived: this machine's spirv-opt wrapper fails (/usr/bin/distrobox: No such file or directory).

Note, not a defect: v_pk_add_f16 (tools/rdna2spirv.py:5739) passes exact_tiny=True unconditionally, and that path silently ignores an omod (v_pk_add_f16 v0, v1, v2 div:2 emits no OpFMul, on main too). Correct today only because no omod is applied there; if one is ever added, it needs the scalar path's not any(m.startswith(("mul:", "div:")) for m in mods) guard.

Verdict: LGTM, no defect found. AMD/NVIDIA driver behaviour not re-checked here (duudiis' hardware run covers it).

AI-assisted review.

@padhossein

Copy link
Copy Markdown
Contributor

Independent f16 narrowing comparison (6d599921). All five targeted tests passed, and I ran 400 additional comparisons against Python binary16 packing (100 per add/sub/subrev/packed-add form, biased to signed subnormals and including overflow and signed zero). Both base and head were bit-exact for all 400 cases. In the generated SPIR-V assembly for those exact fixtures, instruction lines fell from 60,415 to 52,315 (13.4%). Results from the semantic interpreter, synthetic inputs.

AI-assisted (Codex).

In nearest-even mode the overflow select already maps infinity to 0x7C00, so
the separate infinity select goes. An f16 add/sub without omod is exact below
2^-14, so that range needs no rounding and no underflow select.

v_add_f16 goes from 47 to 31 SPIR-V instructions after spirv-opt -O, and
v_pk_add_f16 from 90 to 58. Checked equal on all 2^32 f32 inputs and all 2^32
f16 operand pairs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@tibzejoker
tibzejoker force-pushed the translator/f16-narrowing-size branch from fdb9f80 to 8d19c77 Compare November 22, 2026 18:46
@bobcatchris

Copy link
Copy Markdown
Contributor

Verification on Windows, CPU only, Python 3.12.0, overlay of this PR on origin/main 16282101, run the way CI runs it (python -m unittest discover -s tests/semantic):

  • Full semantic suite with the patch: 4147 tests, OK (396 s). A behaviour-preserving refactor has to leave this unchanged, and it does.
  • The size claim holds. One synthetic listing with a single v_add_f16 emits 272 instruction lines with the patch against 289 on main (-17, about 6% for that op).
  • The new file does drive the lowering (unlike a pure reference-model file): it builds listings, goes through support.translate_lines, and reads mrt0_words from the mini interpreter, comparing with an exact Fraction sum. That is the right shape for this change.

Mutation controls, to see what the file can and cannot catch:

mutation result
re-enable the "flush tiny sums" select inside the exact_tiny branch still OK — that branch is unreachable for sums of two f16s (e is at least 103 against the e < 101 test), which is the PR's own argument
subnormal shift clamp shc = min(sh, 25) → 24 still OK — sh never exceeds 23 for exact sums (smallest is 2^-24)
v_add_f16 lowered to OpFSub FAILED (failures=2): test_add, test_omod_result_is_still_rounded

So the test pins the results of the four ops but, as the PR says, the two steps it deletes are provably unreachable on the exact_tiny path; the whole-suite run is what confirms "same bits" everywhere else.

On unchanged main the new file also passes 5/5, which is expected for a refactor: the value here is the smaller SPIR-V, not a fixed bug. All mutations were reverted; the tree is clean and no game data was read.

@davidesidoti

Copy link
Copy Markdown

Tested 8d19c77 on AMD Radeon RX 9070 XT (RDNA4), Adrenalin 26.11.2 (LLPC, Vulkan 1.4.359), Windows 11 build 26300, llvm-mc 21.1.8: pass.

  • python -m unittest discover -s tests/semantic: 4142 tests OK (3 skipped).
  • scripts/run_gpu_tests.py: 194/194 translated and spirv-val valid; 175/189 passed, 14 skipped, the same outcome per test as main at ec8ec4c (run on the same machine).
  • tools/valu_fuzz.py --family f16 --programs 2000 --seed 1 --wave both: 4000/4000 programs match natively, 0 mismatched, 0 not translated, 0 harness errors; main at ec8ec4c gives the same with the same seed.

(AI-assisted test run.)

@tibzejoker

Copy link
Copy Markdown
Contributor Author

Merged to main in 6e3426d (the branch was force-pushed after the local merge, so GitHub didn't mark it). Closing.

@tibzejoker tibzejoker closed this Nov 22, 2026
ItsNotRexed added a commit that referenced this pull request Nov 22, 2026
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.

6 participants