wave64_emulate_opt: fold a region at most one lane of the wave runs (SHADER-W64-ONE-LANE-FOLD) #2447
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/2447"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Imported from ubiquitarianism/leonida. Originally posted by DadaCap on 2026-11-27T10:17:27Z.
Claimed in the coordination issue as SHADER-W64-ONE-LANE-FOLD (jointly with @OreoFR): https://github.com/ubiquitarianism/leonida/issues/1608#issuecomment-7178187388 (narrowed from SHADER-W64-UNIFORM-EXECZ-BARRIER).
Depends on: none (#2102, which it was built on, is merged).
What and why
Under
--wave64-emulate, a compute program that picks one thread for a tail (clear LDS, then after a barrier sum it up and store) does it withv_cmpx_eq_u32 c, v0orv_cmp_eq_u32 m, c, v0+s_and_saveexec_b64 _, m. Such ans_cbranch_execzregion could not be folded: it has several stores, sometimes a loop, andv_readfirstlane_b32inside, so it went through the emulated rounds. On one 1,024-thread library program this takes the round switch from 639 cases to 33 (spirv-valvalid). A program it changes,lib_cs_00962, was the one active in 3 of 4 compute TDR timeouts @OreoFR saw on NVIDIA.A region whose EXEC holds at most one lane of the workgroup can be folded: no other lane exists to order against, and a
v_readfirstlane_b32in it reads that lane's own value.The rule
_one_lane_in(tools/wave64_emulate_opt.py) is a forward must-analysis that proves EXEC holds at most one lane, intersected at joins:v_cmp(x)_eq_{i,u}32 <constant>, v0, only whilev0(LocalInvocationId.x) has not been written since entry, and only when no two lanes of a wave can sharev0(a one-row group, or rows of whole waves). Compares with modifiers or SDWA are excluded.s_mov/s_and/s_andn2_b64of that mask, saveexecs and later compares.vcc_lodestination counts), any VGPR write tov0(movrel, swaps, memory results), and any EXEC write that is not a recognised narrowing.x_order_barrierbetween its accesses, andv_readfirstlane_b32copies the lane's own value when the region writes no EXEC. Scalar and VCC results of the region must already be dead at its end. The memory kinds it touches still go intox_dirty, so the next conflicting access after the fold still splits.%active.The contract row is in
docs/design.md.Tested
tests/semantic/test_wave64_one_lane_fold.py(hand-written programs, 128 threads in two waves, no game data): the workgroup interpreter oftest_wave64_emulate_opt.py, both invocation orders, compared with the plain round emulation; the constant picks a lane of wave 0, of wave 1, or none, throughv_cmpx_eq_u32and throughv_cmp_eq_u32+s_and_saveexec_b64. Negatives (a compare against another VGPR than the thread id, an overwrittenv0, a compare that is not an equality, rows of 32 threads) must not take the one-lane path and must still match.python -I scripts/run_semantic_tests.py tests/semantic: 501 files, 6,377 tests, 0 failed (351 s, 24 jobs, Windows 11).--no-asm --wave64-emulate, 8 shards, spirv-val on),mainagainst this branch: 2,479 translated andspirv-val-valid both times, the same set; exactly 20 modules change, the other 2,459 are byte-identical.spirv-valon both; 36 one-lane folds in total. A lockstep interpreter run at each program's real workgroup size, comparing memory writes, image texels and LDS betweenmainand this branch, found no divergence in any completed run; 16 of the 20 programs reached a fold (the rest rely on the static argument).TdrDelay=60, GPU timestamps around each dispatch:lib_cs_009621,412 ms mean / 1,754 ms max over 12 dispatches → 212 ms / 231 ms over 9 (about 6.7x). Before this library,lib_cs_00962was the program active in 3 of his 4 device losses (Aftermath timeout). With it: 6 runs, 0 device lost, 0 early crash, the world drawn in 4 of them: https://github.com/ubiquitarianism/leonida/issues/1608#issuecomment-7212426301 and https://github.com/ubiquitarianism/leonida/issues/1608#issuecomment-7212532002n=1per library; picture correctness was not compared.python -I scripts/check_no_game_data.pyon the changed files: clean.GPUs tested: the measurements above (RTX 4070 Laptop, RTX 4080); my own runs on an RTX 5080 (621.24) used a library with this change. No GPU fixture is added: the rule is checked on the CPU interpreter against the round emulation.
AI-assisted: yes (Claude Code, Opus 5.5)
Checklist
mainand merges cleanly (a conflicting pull request is labeledneeds rebase).docs/design.md, with how it was confirmed.🤖 Generated with Claude Code
https://claude.ai/code/session_01Gt9hwNPurxyJ9LAfUbNiYr
Imported from ubiquitarianism/leonida. Originally posted by OreoFR on 2026-11-27T10:18:54Z.
Retail test of this exact head (
7ccbbd876): the 20 library modules this rule changes, swapped into an otherwise current pack. RTX 4070 Laptop 8 GB (profile M), NVIDIA 621.40, Windows 11,TdrDelay=60.lib_cs_00962. In earlier runs it was the program active in 3 of 4 compute timeouts.main+ #2418: no device loss, and no early crash (the0xffffffffffffffffread I saw once with an older runtime didn't come back). With #2440, the world draws in these runs.Caveats:
AI-assisted (Claude Code, Claude Opus 5.5).
Imported from ubiquitarianism/leonida. Originally posted by zmasi on 2026-11-27T11:31:22Z.
Review: COMMENTED
Windows x64 / RTX 3090 GPU and semantic check of #2447 (
7ccbbd876).Environment: Windows 11 x64, NVIDIA GeForce RTX 3090 (driver
610.88, Vulkan1.4.341, compute subgroup32..32),VK_LAYER_KHRONOS_validation1.4.363,llvm-mc21.1.8, SPIRV-Tools1.4.363.1.Code & invariant check
tiduniqueness (tools/rdna2spirv.py:18873):assemble()unconditionally initializes%vgpr[0](v0) toLocalInvocationId.x(c = 0inrange(gen.cs["tid"] + 1)). With linear invocation indext = x + sx * y + sx * sy * zand 64-lane waves[64w, 64w + 63],sy * sz == 1givesx = t, andsx % 64 == 0keepsy,z, andx // 64constant within each wave, sov0is distinct across all 64 lanes of a wave in both cases (and can collide only whensy * sz > 1andsx % 64 != 0, such as32 x 4 x 1)._one_lane_step/_one_lane_inintools/wave64_emulate_opt.py):v_movrel/v_swaprelcleartid,v_swapkills both VGPR operands, and non-v_VGPR-writing ops killn + 1registers sotfedestinations cannot leavev0live intid._TID_EQrejectsmodsand_sdwa(which also excludes_dpp, as DPP ops carry modifier tokens and take VGPR sources), requires an integer immediate paired with a single-VGPRtidoperand, and kills any tracked scalar pair when either half (3 << k) orVCC(1 << _BIT_VCC) may be written.s_andn2_b64ands_andn2_saveexec_b64propagate single-lane status only fromsrc0(src0 & ~src1/ssrc & ~exec), whiles_and_b64accepts either source.v_readfirstlane_b32(tools/rdna2spirv.py:6139, 8106, 18945):emit_folded_regionstill emitsg.x_order_barrier()in uniform control flow beforelbl_dowheng.x_dirtyconflicts withfd["mem_reads"]/fd["mem_writes"], andx_memory_ordercontinues recording(kind, "r"/"w")ing.x_dirtyinside the fold so subsequent wave accesses afterlbl_endremain ordered.v_readfirstlane_b32is permitted only whenone_lane_in[run]holds and no block inregionwritesEXEC(any(blk_info[u][3] for u in region)is false); becauselbl_doexecutes only when%activeis true,EXECcontains solely the executing lane throughout the fold, makingself.dst(a[0], self.src_u(a[1]))exact for both SGPR andvcc_lo/vcc_hidestinations.GPU verification on RTX 3090 (subgroup 32,
VK_LAYER_KHRONOS_validation)Adapted the 128-thread two-wave synthetic program from
tests/semantic/test_wave64_one_lane_fold.py(3 LDS writes including two to one address,s_barrier, LDS readback,v_readfirstlane_b32intos12andvcc_lo, and two buffer stores tos[0:3]offset0, plus lane127's control store to offset4) and ran all four cases throughspirv-as,spirv-val --target-env vulkan1.2, andvk_compute_test <spv> 1 dumpunderVK_LAYER_KHRONOS_validation:v_cmpx_eq_u32_e32 0, v0(wave 0 lane 0,2one_lanefolds):out[0..1] = 25, 134— PASS (0validation errors).v_cmpx_eq_u32_e32 65, v0(wave 1 lane 1,2one_lanefolds):out[0..1] = 90, 134— PASS (0validation errors).v_cmpx_eq_u32_e32 200, v0(no active lane,2one_lanefolds):out[0..1] = 0xeeeeeeee (untouched sentinel), 134— PASS (0validation errors).v_cmp_eq_u32_e64 s[42:43], 3, v0+s_and_saveexec_b64 s[44:45], s[42:43](2one_lanefolds):out[0..1] = 28, 134— PASS (0validation errors).Semantic suites, negative controls & SPIR-V size check
python -I tests/semantic/test_wave64_one_lane_fold.py -v: 3/3 OK.python -I tests/semantic/test_wave64_emulate_opt.py: OK.and (sy * sz == 1 or sx % 64 == 0)intools/rdna2spirv.pymakestest_not_one_lane_keeps_the_rounds(rows of 32 threads) fail immediately (FAILED (failures=1)), confirming the multi-row wave-sharing guard is pinned. Restored.1.32 MBemulated wave64 compute modules in a local build, assembled SPIR-V drops from1,323,800 Bto850,816 B(-35.7%,235totalOpSwitchcases) and1,320,680 Bto847,712 B(-35.8%,235totalOpSwitchcases), bothspirv-valclean.python -I scripts/check_no_game_data.pyon all 4 changed files: clean.No game data. AI-assisted.
Imported from ubiquitarianism/leonida. Originally posted by timbot103 on 2026-11-27T11:41:13Z.
Independently checked head
7ccbbd876on Windows 11 Pro 26200, Vulkan SDK1.4.363.0, WSLllvm-mc 21.1.8, across NVIDIA GeForce RTX 5080 (616.64) and AMD Radeon(TM) Graphics (25.10.30.02), no game files.What passed:
test_wave64_one_lane_fold.py(3/3),test_wave64_emulate_opt.py(34/34),test_loop_ballot_barrier.py(15/15).run_gpu_tests.py --filter cs_w64(LEONIDA_W64_EMULATE=1,LEONIDA_VK_VALIDATION=1): 25/25spirv-valclean; 24/24 PASS on RTX 5080 and 24/24 PASS on AMD Radeon, 0 validation errors.valu_fuzz.py --family mem --wave 64 --emulate --programs 120 --seed 20261126: 120/120 match on RTX 5080 and 120/120 match on AMD Radeon.Three soundness bugs reproduced live (
spirv_mini_interpat7ccbbd876vsorigin/main50ce8f51a):A one-block self-loop inside a single-lane region loses its back-edge (
tools/wave64_emulate_opt.py:1428-1443, 1457-1471;tools/rdna2spirv.py:18905-18911):v_cmpx_eq_u32_e32 vcc, 0, v0; s_cbranch_execz .join), then in one.loop:block incrementv1(init 10), store tomem[0], decrements10(init 2),s_cmp_lg_u32 s10, 0; s_cbranch_scc1 .loop:origin/main(50ce8f51a):mem[0] = 12(2 iterations)#2447(7ccbbd876):mem[0] = 11(2nd iteration silently dropped)A compare writing
exec_locertifies all 64 lanes as a singleton (tools/wave64_emulate_opt.py:1165-1169, 1176-1202;tools/rdna2spirv.py:6315-6319, 6944-6948, 8106-8109):v_cmp_eq_u32_e64 exec_lo, 0, v0leaves lane 0 and lanes 32–63 active (the emitter preservesexec_hi), but the analysis marks all of EXEC as single-lane so a foldedv_readfirstlane_b32 s14, v0reads each upper lane's ownv0instead of0.s14per lane):origin/main(50ce8f51a):lane0=0, lane1=0xee, lane32=0, lane33=0#2447(7ccbbd876):lane0=0, lane1=0xee, lane32=32, lane33=33exec).Implicit VCC carry writes leave stale singleton VCC facts (
tools/wave64_emulate_opt.py:528-534, 1165-1169, 1189-1191;tools/rdna2spirv.py:10376-10383, 10421-10426):v_cmp_eq_u32_e32 vcc, 0, v0, the accepted shorthandv_add_co_ci_u32 v3, v1, v2(v1=0xffffffff, v2=1) implicitly updates VCC for every carrying lane in the emitter, while the analysis only tracks the VGPR destination; a subsequents_and_saveexec_b64then misclassifies full EXEC as single-lane. (Specific to the accepted shorthand; canonical LLVM disassembly prints explicit VCC operands.)v_readfirstlane_b32 s14, v0stored per lane):origin/main(50ce8f51a):lane0=0, lane1=0, lane32=0#2447(7ccbbd876):lane0=0, lane1=1, lane32=32Adding these three cases (plus a positive selector from lanes 32–63, e.g. lane 65 in a 2-wave workgroup) to
test_wave64_one_lane_fold.pywould make the fold airtight. AI-assisted.Imported from ubiquitarianism/leonida. Originally posted by DadaCap on 2026-11-27T11:59:41Z.
@timbot103 thank you, these are real gaps in the analysis, and the repros make them easy to pin. I'm fixing all three in the rule itself (a self-edge region is rejected or gets its loop, a compare that writes only
exec_lo/exec_hino longer certifies the whole EXEC unless the other half is proven empty, and the shorthand carry ops invalidate VCC facts), with your three cases plus a positive selector in lanes 32-63 added totest_wave64_one_lane_fold.py. I'll also report how many corpus modules each fix changes, so it is clear whether @OreoFR's and @quartz-heron-58's retail numbers still apply to the same 20 modules. @zmasi thanks for the GPU and invariant check. AI-assisted (Claude Code).Imported from ubiquitarianism/leonida. Originally posted by MSedgeMC on 2026-11-27T15:22:14Z.
Review: COMMENTED
Verified on the PR branch: python3 -I scripts/run_semantic_tests.py tests/semantic -p test_wave64_one_lane_fold.py -> 1 file, 3 tests, 0 files failed (3 s, 6 jobs). Not approving yet: the branch is 596 commits behind current main, so a rebase is needed before the final diff can be reviewed.
Imported from ubiquitarianism/leonida. Originally posted by DadaCap on 2026-11-27T15:40:23Z.
@timbot103 all three are fixed in
a78040bb1, each with a test that fails on7ccbbd876and passes now:cfg_structure.structurelike a multi-block region, so the emitter keeps the back-edge as anOpLoopMergeloop. Before, the back-edge was dropped. That was already true onmainfor a read-only one-block loop, which ran once. Test: self-loop with and without a store, selector lane 0, 40 and 100. Before: a lane got 11 instead of 12, in 6 cases.exec_lo/exec_hi. A half write of EXEC keeps "at most one lane" only if EXEC already was at most one lane and the value written is a compare, which is 0 in inactive lanes. A thread-id compare into one half no longer certifies the other half. Test: lane 40 read its own value (32) where 0 was expected; it now matches the round emulation.v_{add,sub,subrev}_co_ci_u32 vD, src0, src1is now rewritten where the listing is read (explicit_carry_vccintools/rdna2spirv.py, beforewiden_wave64_masks) into the explicit form with VCC as carry-out and carry-in. The emitter's special case is gone, and every analysis sees the VCC write, not only this one. I checked the other implicit-VCC writers the translator accepts; this short form was the only one not modelled. Test: lane 1 read 1 instead of 0 with the short form; the explicit form already passed.docs/design.md's row for SHADER-W64-ONE-LANE-FOLD now states the three rules.Tested:
test_wave64_one_lane_fold.py: 6/6 pass (8 subtests failed on7ccbbd876). The upper-half selectors and the self-loop with a store still fold as one lane and match.python -I scripts/run_semantic_tests.py tests/semantic): 501 files, 6,380 tests, 0 failed (Windows 11).--no-asm --wave64-emulate,spirv-valon): 2,479 translated and valid onmain, on7ccbbd876and ona78040bb1.a78040bb1against7ccbbd876: 0 modules differ. None of the corpus programs hits the three cases, so the modules @OreoFR and @quartz-heron-58 measured on retail are byte-identical to what this head produces.main.check_no_game_data.pyon the changed files: clean.spirv-val.Found on the way, not changed here: in wave64 the emitter treats
v_cmp ... exec_loas a half write butvcc_loas a full write of the pair. The analysis matches the emitter; whether the hardware writes the whole EXEC pair for the first form is not checked.This comment was AI-assisted (Claude Code, Opus 5.5).
Imported from ubiquitarianism/leonida. Originally posted by Tauwni on 2026-11-27T16:22:19Z.
Retested the new head
a78040bb1(with the three self-loop fixes), merged ontomainec91d695c, on a Mac, where wave64 is always emulated: Apple M3, macOS 26.5.1. No game files.mainmain+ this PRLEONIDA_W64_EMULATE=1The failures are the same on both sides. Translator suite: 503 files, 6393 tests, 0 failed. MEASURED, 1 run each. This says nothing about the game.
AI-assisted (Claude Code, Claude Opus 5.5).
Imported from ubiquitarianism/leonida. Originally posted by kawaii-shakal on 2026-11-27T18:20:39Z.
CPU review on Linux, head
a78040bmerged with mainc0201a80:test_wave64_one_lane_fold.pycopied onto main fails 14 (the one-lane cases,the half-EXEC write and the self-loop), so the tests check the change.
0 failed.
salu_diff --programs 500 --seed 1: 500/500 on main and on that merge.crosslane_fuzz --modes emulate --dpp --ext --programs 300 --seed 1(lavapipe): the same 2 mismatch + 3 hyp_onlyprograms on main and on the merge, so none of them come from these PRs.
_one_lane_stepagainst the ISA and found no soundness problem:s_andn2_saveexec_b64is only trustedthrough its source (EXEC = S0 & ~EXEC), the old EXEC goes on only through
s_and_saveexec_b64, a half-EXEC writeneeds the fact already, and
emit_folded_regionstill orders accesses from before the fold withx_order_barrier, so skippingx_memory_orderinside the fold only drops ordering between the lane's ownaccesses. v0 is
LocalInvocationId.xin the CS prologue, so thetidstart state holds.v_add_co_ci_u32 vD, src0, src1. This PR rewrites itto the explicit form right after the listing is read (
explicit_carry_vcc) and drops the emitter's ownexpansion. #2357 teaches
lane_masks.step,wave64_halves.operands,writes_execandwiden_wave64_masksabout the 3-operand form. With both merged, #2357's branches are not reached in
_translate(the operandsarrive already expanded). They still matter for callers that hand instructions to those helpers directly, so
nothing breaks, but whichever lands second may want to drop the duplicate or say which one is meant to stay. The
two merge together cleanly and pass together (above).
AI-assisted (Claude Code); I ran the tests and checked the results.
Generated by Claude Code
Imported from ubiquitarianism/leonida. Originally posted by OreoFR on 2026-11-27T18:23:34Z.
Merge test on an 8 GB laptop (profile M): game runs and this PR's own tests. A second agent on the same machine recomputed the numbers from the raw logs. AI-assisted (Claude Code, Claude Opus 5.5).
a78040bb1, Windows 11:python -m unittest discover -s tests/semantic -p test_wave64_one_lane_fold.py: 6/6 OK.7ccbbd876, not the current heada78040bb1(later fixes). The new head has not been run in game here.7ccbbd876pack has not crashed in any of the 15 runs made with it since (0 device lost, 0 exceptions).Imported from ubiquitarianism/leonida. Originally posted by DadaCap on 2026-11-27T21:08:12Z.
Full-corpus check of the review fixes, asked by @MoonEyes before merging: whole
shaders/dxbccorpus (wave32 and wave64, not only the library),--no-asm --wave64-emulate,spirv-valon,7ccbbd876(the head OreoFR ran in the game) againsta78040bb1(this head)..spv), and none is only on one side.MEASURED.So the game runs on
7ccbbd876(OreoFR's, and quartz-heron-58's on the library) also cover this head: the three fixes change no module the game uses. They only matter for programs the corpus does not contain.Windows 11, Vulkan SDK 1.4.363.1, 8 shards. This comment was AI-assisted (Claude Code, Opus 5.5).
Imported from ubiquitarianism/leonida. Originally posted by MoonEyes on 2026-11-27T22:51:03Z.
Merge-tested
a78040bb1+ main43a9d562d(clean; also merges cleanly onto current main, including #2435 merged just before):test_wave64_one_lane_fold.py6/6, 14 fail with the code reverted to main; full pytest + semantic suites show no new failure vs main;check_no_game_dataclean. CPU-only tests on Windows 11 / Ryzen 5 3600. In game: OreoFR's runs on an RTX 4070 Laptop 8 GB at7ccbbd876(https://github.com/ProjectLeonida/mandy/pull/2447#issuecomment-7225440289), which carry over to this head: 0 modules differ in the full corpus (https://github.com/ProjectLeonida/mandy/pull/2447#issuecomment-7228168140), spot-checked here on two library programs. The short-form carry fix overlaps #2357; whichever lands second should drop the duplicate.AI-assisted (Claude Code, Claude Opus 5.5)