Skip to content

rdna2spirv: decode only the components a typed load writes; fconst is an OpConstant (SHADER-FORMAT-DECODE-ONE-COMPONENT) - #2439

Merged
aslan2142 merged 3 commits into
ProjectLeonida:mainfrom
OreoFR:shader-format-decode-one
Nov 27, 2026
Merged

aslan2142 merged 3 commits into
ProjectLeonida:mainfrom
OreoFR:shader-format-decode-one

Conversation

@OreoFR

@OreoFR OreoFR commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

Claimed in the coordination issue as: SHADER-FORMAT-DECODE-ONE-COMPONENT

What and why

Two code-size changes in tools/rdna2spirv.py. Neither changes a value.

A typed load decodes only the components it writes. A buffer_load_format_* that takes its format from the V# went through four shared functions, %fmt_dec_c0…%fmt_dec_c3, and every load called all four, even _x. There is now one function, %fmt_dec(format, element, component). A load calls it once per register it writes, with the component that register's DST_SEL field picks (DST_SEL - 4). For DST_SEL 0, 1 or a reserved code, k wraps past 3 and the call's value is thrown away, as before. So _x makes 1 call, _xy 2 and _xyzw 4. The function body is the old per-component code: it computes the channel width and bit offset for each of the four components, as before, and the component parameter picks one with three selects. The rest of the decode is shared and unchanged. It is the same value by construction. The DST_SEL chain at each site is now sel - 4 < 4 ? bounded(decode(sel - 4)) : sel == 1 ? one : 0, the same function of sel as the old five-way chain. MTBUF (tbuffer_load_format_*, a fixed format) and the stores are not touched. A store already makes one encode call per site.

fconst gives an OpConstant %float. fconst used to emit a new OpBitcast %float of the uint constant at every use, and so did tof of a uint constant (float literal operands). Both now return one cached OpConstant %float per bit pattern: %f0 and %f1 for 0 and 1, %fc<bits> for the others. tou of such a constant gives the uint constant back, as it did through the bitcast. float_literal writes the literal so that it assembles to the same 32 bits:

  • a finite value is written as the shortest decimal of the f32's own value, which is exact (-0.0 and the denormals included);
  • an infinity or a NaN is written in the SPIRV-Tools hex-float spelling (0x1.8p+128, payload as stored).

Checked on 24 tricky patterns, NaN payloads included, with SPIRV-Tools 2026.4 spirv-as and tools/spirv_asm.py. The three test interpreters (spirv_mini_interp, spirv_wave_interp, tests/spirv_interp.py) now read that hex-float spelling. Before, only spirv_asm did. Two tests that inspected the old bitcast form now follow the constant (test_alu_sincos's sabotage control, test_image_store_dmask's analyzer), and so does test_bitcast_round_trip's bare Gen.

New tests:

  • tests/semantic/test_buffer_format_decode_one.py with the hand-written fixtures fixtures/typed_load_runtime_{x,xy,xyzw}.asm. The V# comes from the push constants, so the format and DST_SEL are run-time values. The test counts the OpFunctionCalls to %fmt_dec per load (1, 2 and 4). It checks the values against the reference decode for 15 formats and a code outside the table, with identity, swizzled, constant and reserved selectors, and out of bounds. It also checks that _x and _xy match the first registers of _xyzw for all 128 codes with random selectors.
  • tests/semantic/test_fconst_constant.py: the literal assembles back to the same bits (+-0, the smallest and largest denormals, the largest finite values, +-inf, quiet and signalling NaNs with payloads), one constant per value with no instruction emitted, and a translated module (v_sin_f32, v_cvt_norm_i16_f16) whose constants keep their bits and still give the expected words.

The docs/design.md row "Run-time format decode cost" described the four functions. It now describes the one function and how it was checked. No rule changes.

Tested

  • Translator suite, python -I scripts/run_semantic_tests.py tests/semantic: 502 files, 6,385 tests, 0 failed (plain main: 500 files, 6,374 tests, 0 failed). The standalone tests/test_*.py that translate or interpret SPIR-V pass too: 67 under python -I, and 1,406 pytest tests with tests/requirements.txt. test_rcp_iflag_mods and test_translate's gather LOD-bounds test now expect the float constant.

  • Equivalence with main: 22,528 typed loads through the mini interpreter, all bit-identical, translated by main and by this branch. The loads covered _x, _xy, _xyz, _xyzw, d16_x, d16_xy, d16_xyz and d16_xyzw, all 128 format codes, random DST_SEL, byte alignments 0-3, num_records from 0 to in bounds, and random words plus NaN, infinity and denormal patterns. That script is local only.

  • tools/buffer_format_fuzz.py --self-test: ok before and after. Its other modes need an AMD hardware oracle, and the translator side of its model is test_buffer_formats_all.py, which passes.

  • GPU tests (scripts/run_gpu_tests.py, llvm-mc 23.1.6):

    • the typed-load tests all pass: cs_buf_fmt8, cs_fmt_1010102, cs_fmt_d16_xyz, cs_fmt_int_narrow, cs_fmt_sint32, cs_fmt_xy_xyz, cs_fmt_all (336/336 words) and cs_tbuffer_store;
    • d3d12_buffer_uav_test (cs_buf_typed, typed buffer UAVs) passes: 21,394 values, error 0;
    • the whole suite gives 212/269 passed and 55 skipped. Two tests fail, and both fail the same way on main with the same build on this GPU: cs_imgatomic_ext (6 of 64 sint words) and cs_texture_uav (a format without formatless storage access).
  • Corpus slice (--limit 300 --wave64-emulate): 300 translated and 300 pass spirv-val, on main and on this branch. The modules go from 78,480,168 to 74,512,388 bytes (−5.1%).

  • Module size, 3 shaders retranslated locally with the make_game flags (--wave64-emulate). Every module passes spirv-val before and after:

    shader bytes, main → branch instructions, main → branch %fmt_dec calls float bitcasts of a constant
    …CS_ScreenProbes_ActivateProbes 26,327,572 → 25,486,392 (−3.2%) 1,420,419 → 1,383,527 (−2.6%) 13,124 → 3,281 435 → 0
    a …CS_RaytracingResolve_… 5,949,900 → 5,732,252 (−3.7%) 331,911 → 318,620 (−4.0%) 176 → 52 12,571 → 0
    a small pixel shader (control) 42,128 → 41,200 (−2.2%) 2,366 → 2,308 (−2.5%) 0 → 0 59 → 0

    The claim estimated −28% for ActivateProbes with single-component loads. The real gain is smaller. In a minimal program, a _x load costs 200 instructions at its site on main and 189 here (_xyzw: 236 → 216). The calls and the select chain were only a small part of it. The rest is the address, the bounds check, the five dword loads, the window shift and the DST_SEL kind test, and this PR does not change any of that. On top of that, each module drops three of the four decode bodies. 3,281 sites × 11 instructions is about the 36,900 instructions that ActivateProbes loses. I did not measure vkCreateComputePipelines time: a retail test run was using the GPU.

GPUs tested: NVIDIA GeForce RTX 4070 Laptop 8 GB, driver 621.40, Windows 11.

AI-assisted: yes (Claude Code, Claude Opus 5.5)

Checklist

  • Based on current main and merges cleanly (a conflicting pull request is labeled needs rebase).
  • One topic; follow-up work goes in a new pull request.
  • 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. (n/a: no behaviour change)

🤖 Generated with Claude Code

… an OpConstant (SHADER-FORMAT-DECODE-ONE-COMPONENT)

A buffer_load_format_* with a run-time FORMAT called the four per-component
decode functions %fmt_dec_c0..3 at every load, whatever it wrote. One
function %fmt_dec(format, element, component) replaces them, and a load
calls it once per register it writes, with the component that register's
DST_SEL picks: _x makes one call, not four. The function computes the four
components' channel width and offset as before and the parameter selects
one, so the values are the same.

fconst (and tof of a uint constant) emitted a new OpBitcast of the uint
constant at every use; they now give one cached OpConstant %float per bit
pattern, written so spirv-as reads back the same 32 bits (float_literal:
shortest decimal for a finite value, the SPIRV-Tools hex-float spelling for
an infinity or a NaN). The test interpreters read that spelling.

Tests: test_buffer_format_decode_one.py with hand-written fixtures
(calls per load, values for 16 codes, swizzles, out of bounds, _x/_xy
against _xyzw for all 128 codes) and test_fconst_constant.py (exact bits of
+-0, denormals, infinities and NaN payloads).

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

Copy link
Copy Markdown

First compute pipeline creation on RTX 4090. I compared 22a8be16c with its parent d1dff7949 on Windows 11, NVIDIA 616.64. With eight typed loads, the median first creation went from 154.8 to 68.0 ms for _x and from 160.6 to 179.3 ms for _xyzw. The PR was faster in all 72 paired measurements of _x, _xy and _xyz. Full-width loads were slower in 23 of 24 pairs, even though their binaries also shrank.

Load One site, base → PR Eight sites, base → PR Paired change, one / eight sites
_x 30.2 → 21.8 ms 154.8 → 68.0 ms −28.7% / −56.1%
_xy 29.5 → 24.5 ms 149.7 → 90.7 ms −17.0% / −39.7%
_xyz 30.0 → 29.0 ms 153.8 → 122.4 ms −3.9% / −20.1%
_xyzw 31.5 → 34.4 ms 160.6 → 179.3 ms +9.1% / +8.1%

Each row uses synthetic, wave64-emulated compute programs with a runtime buffer descriptor. The eight sites read distinct offsets 256 bytes apart. All components returned by each load feed a per-lane integer checksum. I checked the emitted decoder call counts: four per site on the base and one through four on the PR, according to width.

Method. For each site count and width I varied a live integer literal across 12 matched program pairs, shuffling pair order and running each revision first six times. Each module ran in a fresh process. I timed only vkCreateComputePipelines, with a null application pipeline cache, driver caching left enabled, and validation off. Times in the table are per-revision medians. Percentages are median paired changes. Immediate recreation on the same device took 3.0–6.3 µs across the group medians.

Correctness. All 192 timed dispatches matched the CPU reference for their 64 output words and preserved every other word in the 4 KiB buffer. The timed case used RGBA8_UINT with a Z/X/W/Y swizzle. I then reused one pair per shape with an RGBA32_UINT descriptor selecting W/1/Z/X. All 16 of those dispatches matched under Khronos validation, with zero validation errors. All 192 timed modules passed Vulkan 1.2 SPIR-V validation.

These measurements cover first pipeline creation for small synthetic modules on this driver. The size and load-width mix of a game module could change its result. Measurement claim

@GrahamboJangles

Copy link
Copy Markdown

Reviewed head 22a8be16c vs base d1dff7949 on Windows 11, CPython 3.13.14 (and reran the quick suites on 3.14.9), no GPU, no game data. Coordination re-read first: both #1608 entries for this item read done: SHADER-FORMAT-DECODE-ONE-COMPONENT -> #2439, and no other open PR carries the tag. @ecox982745's RTX 4090 timing comparison is independent of what I ran below.

Passing at head (Windows, python3 -I, per file): the two new suites test_buffer_format_decode_one.py 6 OK (1.8 s) and test_fconst_constant.py 5 OK; the rewritten test_format_decode_table.py 4 OK; and the touched consumers untouched-count-wise: test_rdna2spirv_decode.py 25 OK, test_rcp_iflag_mods.py 5 OK, test_alu_sincos.py 30 OK, test_bitcast_round_trip.py 3 OK, test_image_store_dmask.py 13 OK. Method counts base→head for every modified test file are unchanged (4→4, 25→25, 5→5, 30→30, 3→3, 13→13): the new coverage is the two new files (+6 and +5 methods) plus tightened assertions, nothing replaced. py_compile clean on all touched .py including both interpreter edits. (tests/test_translate.py needs pytest, which isn't on this box — not run here.)

Discrimination run: copied the base d1dff7949 tools/ into a scratch tree together with the head branch's whole tests/semantic/ layer, then ran head's test files against the base translator: test_format_decode_table.py FAILED 2/4 (the shared-decode pin wants %fmt_dec = OpFunction with the %uint component parameter; base emits %fmt_dec_c0..c3 per-component functions), test_buffer_format_decode_one.py FAILED 3/6, test_fconst_constant.py FAILED (10 failures, 54 errors). So all three new/changed pins genuinely catch the old emit. And the failures are confined to shape/count pins — the value-by-value fixtures elsewhere agree between old and new output, which matches the PR's "values bit-identical" claim on the paths I can run.

One trap worth recording for future reviewers: pointing LEONIDA_TOOLS_DIR/PYTHONPATH at a base tools/ copy does NOT swap the translator for the semantic suite — tests/semantic/support.py sits in the script directory and shadows it (sys.path[0]). The mixed-tree copy above is what actually works.

What I did not check here: the GPU side (first-pipeline-creation timings, shader-size deltas on the RTX 4090 are @ecox982745's, reproduced below), and the corpus-wide 22,528-typed-load comparison is the author's. What I verified is the interpreter-side contract: values identical, shared decode function shape pinned (and its size bound test_the_decode_is_small still passing), fconst now a real OpConstant %float with bitcast removal, and the single rewritten line in docs/design.md (the run-time format decode cost row) now matches the emitted shape I saw: one shared %fmt_dec with the component as the last parameter, called once per written register.

Merge state at read time: mergeable=true, mergeStateStatus=unstable, checks still settling, none failed.

No findings on the change. AI-assisted (Hermes agent); the runs above are reproducible on any CPython box without a GPU.

@GrahamboJangles

Copy link
Copy Markdown

Heads-up: stdlib-tests-linux is red at this head — tests/test_f64_conversion.py still pins the old uint-constant-plus-bitcast scale shape that this PR removes.

Failing job: https://github.com/ubiquitarianism/leonida/actions/runs/45962173838/job/140385835209 — test_output_modifiers fails 4/4 parametrized cases (mul:2, mul:4, div:2, clamp div:2), check_conversion line 45:

AssertionError: unexpectedly None : Missing SPIR-V instruction: OpConstant %uint 1073741824

Reproduced locally at this head (22a8be1), pure Python, no GPU:

gh pr checkout 2439 --branch pr2439
python tests/test_f64_conversion.py -v     # FAILED (failures=4)
git checkout main
python tests/test_f64_conversion.py -v     # OK

Root cause is exactly the fconst change. For the mul:2 scale the old translator emits, on main:

%c40000000 = OpConstant %uint 1073741824
%t6 = OpBitcast %float %c40000000
%t7 = OpFMul %float %t5 %t6

and at this head:

%fc40000000 = OpConstant %float 2.0
%t6 = OpFMul %float %t5 %fc40000000

So the disassembly no longer contains an OpConstant %uint <bits> for the scale, and the test's pin (result(rf"OpConstant %uint {scale_bits}") followed by OpBitcast %float {constant}) can never match. The other suites this PR touches stay green, and #2438 / #2435 have stdlib-tests-linux passing, so the regression is specific to this branch — tests/test_f64_conversion.py is just not in the PR's changed-file set.

The emitted form looks semantically fine: the literals here (2.0, 4.0, 0.5) are exact f32 and the %fc<bits:x> id encodes the exact bit pattern, so a minimal fix is to re-pin the test to the new shape rather than revert anything, e.g. in check_conversion replace the constant/bitcast pair with:

    scale = f"%fc{scale_bits:x}"
    self.assertRegex(spv, rf"(?m)^ *{re.escape(scale)} = OpConstant %float ")
    value = result(rf"OpFMul %float {value} {scale}")

which keeps the bit-exactness assertion (the id names the raw bits) without pinning the literal's textual form. Everything before/after that section of check_conversion matched the new emission unchanged in my run, so this is the only stale pin.

Environment for the local runs: CPython 3.13.14 (the repo's activated venv), Windows host, repo clone at head via gh pr checkout, exact command python tests/test_f64_conversion.py -v.

@timbot103

Copy link
Copy Markdown
Contributor

Independently verified head 22a8be16c on Windows 11 Pro 26200, Vulkan SDK 1.4.363.0, WSL llvm-mc 21.1.8, across both NVIDIA GeForce RTX 5080 (Blackwell, driver 616.64) and AMD Radeon(TM) Graphics (driver 25.10.30.02), no game files:

  • Semantic suites (61/61 OK):
    • test_buffer_format_decode_one.py: 6/6 OK
    • test_fconst_constant.py: 5/5 OK
    • test_format_decode_table.py: 4/4 OK
    • test_bitcast_round_trip.py: 3/3 OK
    • test_alu_sincos.py: 30/30 OK
    • test_image_store_dmask.py: 13/13 OK
  • Dual-GPU tools/valu_fuzz.py --wave both --emulate --programs 120 --seed 20261126 (960/960 shader executions matched):
    • RTX 5080, --family mem: 240/240 match (0 mismatched, 0 skipped, 0 harness errors)
    • RTX 5080, --family f16: 240/240 match (0 mismatched, 0 skipped, 0 harness errors)
    • AMD Radeon, --family mem: 240/240 match (0 mismatched, 0 skipped, 0 harness errors)
    • AMD Radeon, --family f16: 240/240 match (0 mismatched, 0 skipped, 0 harness errors)
  • Dual-GPU scripts/run_gpu_tests.py --require-pass with LEONIDA_VK_VALIDATION=1:
    • --filter cs_fmt (cs_fmt_1010102, cs_fmt_d16_xyz, cs_fmt_int_narrow, cs_fmt_sint32, cs_fmt_xy_xyz): 5/5 PASS on RTX 5080 and 5/5 PASS on AMD Radeon, 0 validation errors.
    • --filter cs_buf (cs_buf_fmt8, cs_buf_load_sub, cs_buf_swizzle, cs_buf_tail): 4/4 runnable PASS on RTX 5080 and 4/4 runnable PASS on AMD Radeon, 0 validation errors (cs_buf_counter and cs_buf_typed skipped as expected).

No regressions observed on Blackwell or AMD Radeon. AI-assisted.

@aslan2142

Copy link
Copy Markdown
Collaborator

Reviewed at 22a8be16c. Holding for one fix.

AI-assisted (Claude Code, Claude Opus 5.5 and Claude Fable 5.2)

OreoFR and others added 2 commits November 27, 2026 11:54
…me bits

fconst now emits one cached OpConstant %float per value (%fc<bits>) instead
of an OpConstant %uint bitcast at each use, so the v_cvt_f32_f64 omod check
looks for %fc<scale bits> = OpConstant %float and checks that its literal
gives back exactly the scale's 32 bits. The rest of the data flow is pinned
as before.

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

OreoFR commented Nov 27, 2026

Copy link
Copy Markdown
Contributor Author

Fixed in 53d138d2d, on top of a merge of current main (63185f4a3, which includes #2418, #2440 and #2432; no conflicts).

The 4 failures were the mul:2, mul:4, div:2 and clamp div:2 cases of test_output_modifiers. All 4 were about the text form only. The constant is intended: fconst and tof() of a uint constant now emit one cached %fc<bits> = OpConstant %float instead of OpConstant %uint plus an OpBitcast at each use. The values are unchanged. I checked this by translating all 6 cases with main's tools/ and with this branch's, and comparing the two:

  • The float literal of each scale converts back to the same 32 bits as main's uint constant (0x40000000, 0x40800000, 0x3f000000).
  • Everything after OpFConvert is identical once the bitcast is replaced by the float constant and the temporary ids are renumbered.
  • Each head module passes spirv-as and spirv-val --target-env vulkan1.2, and its binary holds a 4-word OpConstant whose value word is exactly that bit pattern.

Test change (tests/test_f64_conversion.py): the check now looks for %fc<scale bits> = OpConstant %float <lit> and asserts that <lit> gives back exactly scale_bits as an f32. It then expects OpFMul with that id. The rest of the data flow is pinned as before (the clamp NaN select, FClamp, the bitcast to uint and the store).

Local runs (Windows 11, CPython 3.13, python -I, no GPU):

  • tests/test_f64_conversion.py: OK.
  • The stdlib-tests-linux loop (same file filter as ci.yml): 508 files and 8334 tests. 5 files fail here, and each fails the same way on main on this Windows host. test_run_game_wine needs fcntl. test_bink_names, test_opus_tags, test_world_names and test_calibrated_texture_extra check Windows path or permission messages. None of them comes from this change.
  • scripts/run_semantic_tests.py tests/semantic: 502 files, 6385 tests, 0 failed.
  • scripts/check_no_game_data.py on the changed files: clean.

AI-assisted (Claude Code, Claude Opus 5.5).

@aslan2142

Copy link
Copy Markdown
Collaborator

Merging 53d138d2d on main 63185f4a3.

  • The tests/test_f64_conversion.py hold from 22a8be16c is fixed (checks %fc<bits> = OpConstant %float and its f32 bit round-trip).
  • Tested locally at 53d138d2d (Linux, python3 -I, no game data): test_ci_registration.py (18/18), full stdlib-tests loop (508/508 files), run_semantic_tests.py (502 files, 6,385 tests, 0 failed), pytest tests/test_translate.py (720 passed), buffer_format_fuzz.py --self-test, spirv-as/spirv-val (24/24 TRICKY literals bit-exact and typed_load_runtime_{x,xy,xyzw} valid), and check_no_game_data.py clean.
  • Translator unchanged since 22a8be16c, which already passed independent GPU checks on RTX 4090 (@ecox982745), RTX 5080 and AMD Radeon (@timbot103), and the Wine iGPU suite (RADV, Mesa 26.3.1).

AI-assisted review (Antigravity, Gemini).

@aslan2142
aslan2142 merged commit a3bafd0 into ProjectLeonida:main Nov 27, 2026
7 of 12 checks passed
real-rusher added a commit to real-rusher/leonida that referenced this pull request Nov 27, 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.

5 participants