Skip to content

SHADER-480: rdna2spirv atomic natural alignment (gfx1036) and buffer_atomic_{fmin,fmax} - #2710

Merged
ItsNotRexed merged 2 commits into
ItsNotRexed:mainfrom
TheAirborneCoder:shader-atomic-align-fminmax
Nov 23, 2026
Merged

ItsNotRexed merged 2 commits into
ItsNotRexed:mainfrom
TheAirborneCoder:shader-atomic-align-fminmax

Conversation

@TheAirborneCoder

Copy link
Copy Markdown
Contributor

Claimed in #2516 (#2516 (comment)).

Summary

  1. Enforce natural alignment on all buffer and global atomics (measured natively on RDNA2 gfx1036, wave32 & wave64):
    • Added Gen.atomic_aligned(addr, align_bytes) (OpUConvert %uint + OpBitwiseAnd + OpIEqual ... 0) and guarded all six atomic emitters (global_atomic, global_atomic_float, global_atomic_x2, buffer_atomic, buffer_atomic_float, buffer_atomic_x2) on (addr & 3) == 0 (32-bit) or (addr & 7) == 0 (64-bit _x2).
    • Unified the skipped-path return value to OpPhi ... 0 written via Gen.dst(...), fixing global_atomic* so active unaligned lanes receive 0 / (0, 0) while inactive lanes (EXEC = 0) preserve vdst — matching real gfx1036 hardware.
  2. Confirmed all-or-nothing 8-byte partial bounds for buffer_atomic*_x2 (answering the prior "not measured" note in Gen.buffer_atomic_x2):
    • Measured natively on gfx1036 across all four OOB_SELECT modes (wave32 and wave64), confirming that fixed_fmt=62 (all-or-nothing 8-byte bounds) matches hardware exactly.
  3. Implement buffer_atomic_fmin and buffer_atomic_fmax (+2 RDNA2 ISA coverage):
    • Factored the core-SPIR-V OpAtomicCompareExchange + GLSL.std.450 NMin/NMax CAS loop into Gen._emit_atomic_fminmax_cas (no SPV_EXT_shader_atomic_float_min_max capability required) and added Gen.buffer_atomic_float, enforcing V# bounds, 4-byte natural alignment, and glc return (lds and non-1-VGPR vdata raise Unsupported).
    • Added a unique-topic contract row in docs/design.md documenting the measurements and the measured L2 atomic-unit approximation (sNaN quieting and f32 subnormal flushing to +0, not modelled by NMin/NMax).

Native RDNA2 (gfx1036) hardware measurements

Measured via tools/hw_oracle/ in both wave32 and wave64 on AMD Radeon(TM) Graphics (gfx1036), Windows driver 32.0.21042.62 (wave32 and wave64 agreed on every probe):

  • Natural alignment (buffer_atomic*, buffer_atomic*_x2, buffer_atomic_fmin/fmax, buffer_atomic_cmpswap, global_atomic*, global_atomic*_x2, global_atomic_fmin):
    • 32-bit atomics require (addr & 3) == 0: offset=1, offset=2, base+2 offset=0 are dropped; base+2 offset=2 succeeds.
    • 64-bit _x2 atomics require (addr & 7) == 0: offset=2, offset=4, base+4 offset=0, stride=16 off=4, stride=12 off=4 are dropped even under OOB_SELECT = 2 (DISABLED); base+4 offset=4 succeeds.
    • Dropped accesses leave memory untouched, write 0 / (0, 0) to vdst/vdata on active glc lanes, and preserve vdst/vdata on inactive lanes (EXEC = 0).
  • 64-bit partial bounds (buffer_atomic_{swap,and,or,xor}_x2):
    • OOB_SELECT = 3 (RAW): 0/8 and 8/16 succeed; 0/7, 0/5, 0/4, 8/15, 8/12 drop all-or-nothing.
    • OOB_SELECT = 0 (STRUCTURED_WITH_OFFSET): stride=8 off=0, stride=16 off=8, stride=12 off=0 succeed; stride=7 off=0, stride=12 off=8, stride=8 idx=1 drop.
    • OOB_SELECT = 1 (STRUCTURED): idx < num_records (0/4, 0/8, 8/8 succeed).
    • OOB_SELECT = 2 (DISABLED): num_records != 0 (8/8 succeeds; num_records == 0 drops).
  • buffer_atomic_fmin / buffer_atomic_fmax:
    • Normal floats, ±inf, -0 vs +0 (fmin(-0, +0) = -0, fmax(-0, +0) = +0), and qNaN (returns non-NaN operand) match NMin/NMax.
    • L2 atomic unit also quiets sNaN (0x7f800001 -> 0x7fc00001) and flushes f32 subnormals (0x00000001, 0x00000002) to +0 (documented as a known approximation in docs/design.md).

Notes on sibling PRs

Verification

  • AI-assisted: Yes (developed with coding-agent assistance).
  • Hardware / Driver: AMD Radeon(TM) Graphics (gfx1036), Windows driver 32.0.21042.62 (native RDNA2 ISA probes via tools/hw_oracle/, wave32 & wave64). Local spirv-val / Vulkan SDK was not installed in this environment; SPIR-V structure, dominance, OpSelectionMerge/OpLoopMerge/OpPhi invariants, and execution were verified via spirv_mini_interp and full semantic test runs.
  • Tests run:
    • python -I tests/semantic/test_buffer_atomic_fminmax_and_align.py -v — 10/10 passed
    • python -m unittest discover -s tests/semantic — 2,577 ran, OK (3 skipped, 0 failures)
    • python -I tools/mem_diff.py --programs 200 --family buffer_atomic --seed 42 — 200/200 pass, 0 mismatch
    • python -m compileall -q make_game.py tools tests — OK
    • python -I tests/semantic/regen_fixtures.py --check — OK
    • python -I tests/test_docs_links.py, test_docs_list_items.py, test_docs_repo_paths.py, test_tool_startup.py, test_tool_stdout_encoding.py, test_text_write_line_endings.py, test_shader_checks.py (60/60), test_shader_meta.py (15/15), test_isa_coverage.py (10/10, 3 skipped) — all OK

@TheAirborneCoder TheAirborneCoder changed the title rdna2spirv: enforce atomic natural alignment (gfx1036) and add buffer_atomic_{fmin,fmax} SHADER-480: rdna2spirv atomic natural alignment (gfx1036) and buffer_atomic_{fmin,fmax} Nov 22, 2026
@duudiis

duudiis commented Nov 22, 2026

Copy link
Copy Markdown

Independent Vulkan check of caf085c on RTX 5070 / 621.24. All 10,240 returned words matched across wave32 and emulated wave64, with aligned/unaligned MUBUF and GLOBAL operations, 32-bit and _x2 alignment, base + offset compensation, and inactive lanes. The target words and sentinels also matched. For float min/max I checked signed zeros in both orders, infinities, quiet NaNs and seeded normal operands. Both modules passed spirv-val --target-env vulkan1.2 and all ten submitted semantic tests passed.

One issue in _emit_atomic_fminmax_cas: the initial read is a plain OpLoad on the address that other invocations can update with OpAtomicCompareExchange. With concurrent updates and no ordering between those accesses, this is a data race under the Vulkan memory model. This was already true of the global path and now also applies to the new MUBUF path. A relaxed device-scope OpAtomicLoad, with the same scope and semantics as the CAS, keeps the seed read atomic too.

I verified that replacement locally. Both modules validated, and 128 contended workgroups produced the expected final max and 6,144 old-value returns consistent with a valid atomic order. The mini-interpreter on this base needs to recognize OpAtomicLoad through its existing pointer-read path. With that local addition all ten semantic tests passed again. The race finding is from the memory model, not a reproduced corruption on this driver.

@kapitche

kapitche commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Tested on Linux (WSL2 Ubuntu), Python 3.10.12, CPU only: pass. With upstream/main merged (clean), tests/semantic/test_buffer_atomic_fminmax_and_align.py runs 10 tests, OK. Negative control: restoring tools/rdna2spirv.py to upstream/main makes the tests fail (25 failures, 64 errors). Hardware measurements in the new design.md row are not reproducible here. Trial merge with #2722 conflicts in docs/design.md only: both add a row at the same spot in the contract table, keep both; rdna2spirv.py merges cleanly, and #2711 and #2715 merge cleanly.

@ricarmandoagent

Copy link
Copy Markdown

Additional check on caf085c6cdb71993095931db5d28bf2eee188f9c (base 49475796) on Linux: Bazzite 45 / Linux 7.3.4, Python 3.15.2, GCC not involved; NVIDIA GeForce RTX 4060 (Ada, driver 620.70.06, Vulkan 1.4.357).

The semantic sweep and the negative-control counts above are confirmed here:

  • Head: python3 -I tests/semantic/test_buffer_atomic_fminmax_and_align.py -v -> 10 tests OK.
  • Negative control, tools/rdna2spirv.py restored to 49475796, same command -> FAILED (failures=25, errors=64), i.e. the same counts kapitche reports. The first error is the expected one: AssertionError: 'OpUConvert %uint' not found (no alignment guard in the old translation).

On the data-race point raised above, confirmed from the emitted SPIR-V. A one-lane buffer_atomic_fmax v2, v1, s[8:11], 0 offen glc shader translated by this head gives this CAS loop:

%t52 = OpAccessChain %_ptr_PSB_uint %t51 %c0
%t53 = OpLoad %uint %t52 Aligned 4          <-- non-atomic seed read
...
%t61 = OpPhi %uint %t53 %t46_do %t65 %t48_cont
%t65 = OpAtomicCompareExchange %uint %t52 %c1 %c0 %c0 %t64 %t61

The seed read %t53 is a plain OpLoad of the same storage that concurrent invocations update with a device-scope OpAtomicCompareExchange, with no ordering between them — the data race described above. grep -c OpAtomicLoad tools/rdna2spirv.py is 0, so the translator never emits an atomic load; the issue is pre-existing on the global path and now also on the new MUBUF path. The fix the comment above verified (an OpAtomicLoad with the CAS's scope and semantics, and spirv_mini_interp support for it) is the right shape.

What this machine cannot confirm: the gfx1036 measurements themselves (native RDNA2, not reproducible on Ada), and the translated hardware path — this PR adds no GPU fixture for buffer_atomic_fmin/fmax or the alignment guards, so beyond the CPU interpreter and spirv-val there is nothing for the 4060 to run. The alignment/return-value rules stay native-only evidence.

Verdict: LGTM for the semantic logic; the non-atomic seed load is the one thing to fix before merge.

AI-assisted review.

@TheMrBeez

Copy link
Copy Markdown

Tested caf085c (base 49475796) on a second gfx1036 and an RTX 5080, Windows 11 Pro 10.0.26200: pass, with one correction to the subnormal note in the new docs/design.md row (below). AI-assisted run, synthetic shaders only, no game files.

Native hardware, independent of the PR's own probes. AMD Radeon(TM) Graphics, the RDNA2 iGPU of a Ryzen 9 9950X3D (gfx1036, PCI 1002:13C0), AMD driver 32.0.21030.2001 (a different version from the PR's 32.0.21042.62), tools/hw_oracle HIP launcher, AMD clang from rocm-sdk-core 10.0.0. I wrote my own raw kernels from the claims in the description, with the expected values fixed before running. Each case reads back the returned VGPR words and the 8 target dwords. 53 cases × wave32 and wave64, each run under both denorm32 = 0 (the assembler's default) and denorm32 = 3. All 48 non-subnormal cases match in both modes and both wave sizes:

Claim Cases Result
32-bit natural alignment (buffer_atomic_add, buffer_atomic_cmpswap, global_atomic_add) offen 1/2/3, offset:1/2, V# base+2 with off 0 (dropped); base+2 with offen 2, offen 4, global +4 (succeed); offen 2 under DISABLED (dropped) ✓
64-bit natural alignment (buffer_atomic_swap_x2, global_atomic_swap_x2) offen 2/4, base+4 off 0, global +4 (dropped; offen 4 also under DISABLED); offen 8, base+4 offen 4, global +8 (succeed) ✓
A dropped access leaves memory untouched and returns 0 / (0, 0) on an active glc lane all the dropped cases above ✓
An inactive lane keeps its VGPR 2 lanes, lane 1 off in EXEC (preset 0xCAFEBABE), lane 0 unaligned lane 0 → 0, lane 1 → cafebabe ✓
_x2 RAW bounds are all-or-nothing 0/8 and 8/16 succeed; 0/7, 0/4 and 8/12 drop both dwords ✓
buffer_atomic_fmin/fmax 2 vs 1, ±0 in both orders and both ops, ±inf, qNaN in either operand (non-NaN wins), unaligned offen 2 dropped ✓
sNaN is quieted fmin(0x7f800001, 0x7f800001) → 0x7fc00001, under both denorm32 values ✓

The aligned control cases did modify memory as expected, so the dropped cases aren't an artefact of the harness.

Correction: the subnormal flush follows the wave's MODE.denorm32 and keeps the sign. It isn't a fixed property of the L2 atomic unit. The five subnormal cases, identical in wave32 and wave64 (memory word after the atomic; the returned old value is always the raw word):

Case (mem, data) denorm32 = 0 denorm32 = 3
fmax(0x00000001, 0x00000002) 0x00000000 0x00000002
fmin(0x00000001, 0x00000002) 0x00000000 0x00000001
fmax(0x80000001, 0x80000002) 0x80000000 (−0) 0x80000001
fmin(0x00000003, 1.0) 0x00000000 0x00000003
fmax(0x00000003, −0) 0x00000000 0x00000003

So with denormals enabled the result is exact NMin/NMax, and with them flushed a negative subnormal becomes −0, not +0. The row's "known approximation: the gfx1036 L2 atomic unit … flushes f32 subnormals (0x00000001, 0x00000002) to +0" should say the operands are flushed to a signed zero when the shader's denorm32 flushes, and are kept otherwise. Only the sNaN quieting is independent of MODE. I haven't checked how the translator's float controls interact with this.

Vulkan regression run (scripts/run_gpu_tests.py), PR head against main at the base, same test-program build:

Device main 4947579 PR caf085c
RTX 5080, NVIDIA 621.01, subgroup 32 139/185, 46 skipped (wave64) 139/185, 46 skipped
RTX 5080, LEONIDA_W64_EMULATE=1 170/185, 15 skipped 170/185, 15 skipped
gfx1036 iGPU, AMD 32.0.21030.2001, subgroup 32..64 170/185, 15 skipped 170/185, 15 skipped

No failures on either side. Tools: MSVC (VS 2022 Build Tools), Windows SDK 10.0.26100, Vulkan SDK 1.4.363.0 (SPIRV-Tools v2026.4), llvm-mc from rocm-sdk-core 10.0.0 (AMD LLVM 23.0.0git), Python 3.12.10.

CPU: tests/semantic/test_buffer_atomic_fminmax_and_align.py 10/10 OK; python -m unittest discover -s tests/semantic 2,577 tests OK (3 skipped); compileall OK.

I didn't re-check the non-atomic seed OpLoad in _emit_atomic_fminmax_cas that @duudiis and @ricarmandoagent already raised. My hardware cases are single-lane, so they say nothing about contention. The probe script is a standalone file that uses only tools/hw_oracle; I can post it if it's useful.

@whoalin1

Copy link
Copy Markdown
Contributor

Tested caf085c6cdb71993095931db5d28bf2eee188f9c on AMD Radeon(TM) Graphics (RDNA2, gfx1036, device id 0x164e), AMD Windows driver 24.10.24 (Vulkan driver 2.0.302), Vulkan 1.3.280, maxPushConstantsSize 128, subgroup 32..64: pass for the CPU suites, and the alignment guard and buffer_atomic_{fmin,fmax} are now confirmed executing on gfx1036 silicon, which the PR itself could not do (you noted no Vulkan SDK and no GPU at hand).

Your own checks, reproduced.

$ py -3.14 -I tests/semantic/test_buffer_atomic_fminmax_and_align.py -v
Ran 10 tests in 3.142s
OK
$ py -3.14 -I tools/mem_diff.py --programs 200 --family buffer_atomic --seed 42
200 programs (seed 42): 200 pass, 0 mismatch, 0 skipped, 0 harness errors

Both match your counts. Note mem_diff is CPU-only (reference model vs spirv_mini_interp), so it does not exercise the GPU path at all.

GPU check, hand-written and not pushed. Two synthetic compute shaders using the vk_compute_test harness's raw V# (s[0:3], OOB_SELECT 3, num_records max, buffer pre-filled 0xee), thread 0 only. cs_atomic_align runs: store 100 at byte 0; buffer_atomic_add of 5 at byte 1 (glc); buffer_atomic_add of 5 at byte 0 (glc); buffer_atomic_fmin of 1.0 at byte 4 after 2.0 (glc); buffer_atomic_fmax of 3.0 there (glc); read both words back.

$ LLVM_MC="wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc" py -3.14 -I runtime/test/shaders/build.py <out> cs_atomic_align
1 shaders: 1 translated, 1 pass spirv-val
$ VK_LOADER_DRIVERS_SELECT='*amd-vulkan*' LEONIDA_VK_DEVICE="AMD Radeon" runtime/build/vk_compute_test.exe <out>/spirv/cs_atomic_align.spv 1 dump
device: AMD Radeon(TM) Graphics (subgroup 32..64)
out[0..7] = 0 100 1073741824 1065353216 105 1077936128 4008636142 4008636142

That is 0, 100, 2.0, 1.0, 105, 3.0, 0xeeeeeeee, 0xeeeeeeee: the unaligned add returned 0 and left memory alone, the aligned one returned 100 and left 105, fmin returned 2.0 and left 1.0, fmax returned 1.0 and left 3.0. Every rule in your design row reproduces on this driver.

Before/after on the same GPU, which is where this gets interesting. On main 16282101, cs_atomic_align does not translate at all (1 shaders: 0 translated, buffer_atomic_fmin unknown). The alignment half alone (cs_atomic_align2: the same two adds without the float ops) does translate on main, and there the unaligned atomic is not harmless:

main 16282101:  out[0..7] = 100 3735928659 3735928664 4008636142 ...
this PR:        out[0..7] = 0   100        105        4008636142 ...

On main the unaligned OpAtomicAdd returned 100 and left 0xDEADBEF3 in the word that held 100; the following aligned add then returned that corrupted value. So on this driver the guard is not cosmetic: without it the misaligned atomic is lowered into something that does change memory, which is the opposite of what the native MUFU/MUBUF atomic does. With your guard the word is still 100 when the aligned add returns it. Worth wording the design row that way — the guard's job is to keep the SPIR-V-to-ISA path matching the native atomic, not only to reproduce a rule the hardware already enforces for free.

Gen.dst is the right write for the inactive-lane case: dst() with eager=False emits OpSelect active val old, so an inactive lane keeps its prior VGPR while an active skipped lane gets the 0 phi. The _emit_atomic_fminmax_cas refactor also removes the duplicated five-label loop; the phi at lbl_end still takes pre captured before OpSelectionMerge, which is what the old code needed too.

Unverified and left open: global_atomic* alignment and the _x2 8-byte partial-bounds matrix. My probe covers buffer_atomic* 32-bit only — I did not build a global_atomic probe or an _x2 bounds matrix, and nothing in the repo runs buffer atomics on a GPU, so your measurements for those rows still rest on your own hw_oracle run on driver 32.0.21042.62. This driver is 24.10.24, so that gap is worth closing on hardware before merge if you can.

AI-assisted (Capy, DeepSeek V4.1 Flash). Synthetic shaders only, no game data, nothing pushed.

@Jadiac5

Jadiac5 commented Nov 22, 2026

Copy link
Copy Markdown
Contributor

Corpus run of caf085c6 against its merge base 49475796, shard 0 of 8 (3,313 of 26,503 shaders), Windows 11, Python 3.12, spirv-val from Vulkan SDK 1.4.363.1: no regression

translated spirv-val valid modules changed
base 49475796 3,313 / 3,313 3,313
this PR caf085c6 3,313 / 3,313 3,313 117
  • No shader fails before or after, so the set of failing shaders is unchanged (empty). In particular the new alignment guard refuses no shader of this shard.
  • The 117 changed modules are 78 CS (of 326) and 39 PS (of 1,521), all larger than before. The index is identical entry for entry.
  • The PR text says spirv-val was not installed where it was written; all 117 changed modules pass spirv-val here.
  • Not done: shards 1–7, no GPU run of the changed modules.

AI-assisted (Claude Code). Counts only; nothing from the game files is included.

@TheAirborneCoder

Copy link
Copy Markdown
Contributor Author

Thank you everyone for the thorough reviews and independent GPU/corpus runs — @duudiis, @ricarmandoagent, @TheMrBeez, and @whoalin1!

Addressed both reviewer findings in bd935b50:

  1. Atomic CAS seed load (@duudiis, @ricarmandoagent): Changed Gen._emit_atomic_fminmax_cas in tools/rdna2spirv.py from plain OpLoad %uint %p Aligned 4 to relaxed Device-scope OpAtomicLoad %uint %p %c1 %c0 (matching OpAtomicCompareExchange) so there is no mixed atomic/non-atomic data race under the Vulkan memory model. Added OpAtomicLoad support to tests/semantic/spirv_mini_interp.py and structural assertions in tests/semantic/test_buffer_atomic_fminmax_and_align.py covering both buffer_atomic_{fmin,fmax} and global_atomic_{fmin,fmax}.
  2. docs/design.md subnormal & driver notes (@TheMrBeez, @whoalin1): Corrected the known approximation note to record that sNaN quieting (0x7f800001 -> 0x7fc00001) is MODE-independent while f32 subnormal handling follows MODE.denorm32 and preserves sign (denorm32=0 flushes subnormals to signed zero — e.g. fmax(0x80000001, 0x80000002) -> 0x80000000 (-0), fmax(0x00000001, 0x00000002) -> +0 — whereas denorm32=3 keeps subnormals and NMin/NMax is exact), and noted the independent gfx1036 (driver 24.10.24) before/after confirmation where an unguarded unaligned OpAtomicAdd corrupted the aligned dword (100 -> 0xDEADBEF3).

Re-verified locally:

  • python -I tests/semantic/test_buffer_atomic_fminmax_and_align.py -v: 10/10 OK
  • python -I tests/semantic/test_global_atomics.py -v: 12/12 OK
  • python -I tools/mem_diff.py --programs 200 --family buffer_atomic --seed 42: 200 pass, 0 mismatch, 0 skipped, 0 harness errors
  • python -I tests/semantic/regen_fixtures.py --check: OK
  • python -I tests/test_docs_links.py & tests/test_docs_repo_paths.py: OK
  • python -m compileall -q make_game.py tools tests: OK

(AI-assisted.)

@sperm

sperm commented Nov 23, 2026

Copy link
Copy Markdown

Tested 2d2a405 (a re-test at the new head) on AMD Radeon RX 9070 XT (RADV GFX1201, wave32/64) and the Ryzen 7 9800X3D iGPU (RADV RAPHAEL_MENDOCINO, gfx1036), Mesa 26.2.6, Linux 7.3.4: pass, no regressions.

No game files. AI-assisted.

@kapitche

Copy link
Copy Markdown
Contributor

Tested 2d2a405 merged with main 98fa503: redundant. Merging this head into main 98fa503 gives a tree identical to main: the changes are already in main through merge commit 5fcc81f ("Merge pull request #2710"). Nothing left to test; this PR can probably be closed.

@ItsNotRexed
ItsNotRexed merged commit ce1c915 into ItsNotRexed:main Nov 23, 2026
3 of 10 checks passed
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.

9 participants