d3d12-shader: make chains() and loop-counter lowering deterministic (D3D12-SHADER-DETERMINISTIC-EMIT, carry of #2872) #3059
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/3059"
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 MoonEyes on 2026-12-02T06:44:31Z.
Claimed in the coordination issue as: D3D12-SHADER-DETERMINISTIC-EMIT (the claim of the original author, https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7311583627)
What and why
Carry of #2872 (kirigayakazima), in conflict with
mainsince both sides appended a test at the end of the same module ind3d12/crates/leonida-shader/src/emit/bitcode/opt.rs. This branch ismainmerged with the head of #2872, so the author's commit is kept. My only change is the merge: both tests stay.The change itself is #2872's:
chains()builds its per-block plans intree.orderinstead of iterating aHashMap, and the loop counters inlower.rsuse aBTreeMap, so the emitted instruction IDs no longer depend on the run (chains_emits_deterministic_instruction_ids_across_blockspins it).Tested
Windows 11, no GPU, no game files, on current
mainplus this branch:cargo test -p leonida-shader --lib: 421 passed, 0 failed, 5 ignored.cargo clippy --locked -p leonida-shader -- -D warnings: clean.GPUs tested: n/a (translator unit tests only)
AI-assisted: yes (Claude Code)
Checklist
mainand merges cleanly.docs/design.md. (n/a: no new rule, an ordering fix)Supersedes #2872 once merged; the original stays open until a maintainer decides.
AI-assisted (Claude Code)
🤖 Generated with Claude Code
Imported from ubiquitarianism/leonida. Originally posted by Kal0s-design on 2026-12-02T07:36:58Z.
A red/green and the full suite on a card, since the description has neither. Windows 11, MSVC toolchain 1.98.1. Head
5d47d4f57merged into currentmain229d352ee: the merge is clean.Red/green. I took
main'sopt.rsand added only the new test,chains_emits_deterministic_instruction_ids_across_blocks. It fails 5 runs of 5, and the block order differs every run:That is the
HashMaporder changing from one process to the next. With the change it passes 5 runs of 5.cargo test -p leonida-shader --lib, with an NVIDIA card present, so the card-backed tests ran too: 428 passed, 0 failed, 6 ignored. I touchedbuild.rsfirst so the translator's source hash was fresh.cargo clippy -p leonida-shader --lib --tests: no warning inopt.rsorlower.rs.A note on
lower.rs:mainalready sorted the counter headers before walking them (headers.sort_unstable()), so theBTreeMapthere keeps the same order rather than fixing one. The nondeterminism this fixes is the one inchains().Not checked: the game, and AMD hardware.
GPUs tested: one NVIDIA desktop card.
AI-assisted: yes (Claude Code).
Imported from ubiquitarianism/leonida. Originally posted by enlight3d on 2026-12-02T08:20:16Z.
RUN (independent run on Windows, #3059 head
5d47d4f57, merged locally intomainf37c4a87dwithgit merge --no-ff, no conflicts. The head already contains thatmain, so the merge adds only this pull request's diff: 2 files, +76/-15. Its added and removed lines are the same as in #2872's commit9bb420346, so the carry leaves the author's change as it was.main'sbounded_budget_caps_wide_phi_dagis still in place, just above the new test. CI on the head: change-scope, check, d3d12 (windows-latest), linux-python-and-viewer, no-game-data and semantic-tests all pass.)Commands, in
d3d12/, target x86_64-pc-windows-msvc, toolchain 1.98.1, all with--locked, at low priority,RUST_TEST_THREADS=8, one target folder per side:cargo test -p leonida-shader --no-fail-fast: main 420 passed / 0 failed / 5 ignored; merge 421 / 0 / 5 (the new test). Some of these tests run on the GPU, here an RTX 3090.cargo test -p leonida-shader --no-fail-fast --features diagnostics: main 420 / 0 / 5; merge 421 / 0 / 5.main'sopt.rswith only this pull request's test added and its production hunk left out.cargo test -p leonida-shader --lib chains_emits_deterministic, run in 3 separate processes, fails 3 times out of 3 on the monotonic assertion, with a different order each time:[[36, 37], [34, 35], [38, 39], [40, 41], [30, 31], [32, 33]],[[32, 33], [34, 35], [38, 39], [36, 37], [40, 41], [30, 31]],[[30, 31], [32, 33], [36, 37], [34, 35], [40, 41], [38, 39]]. That is the reason the pull request gives: the blocks were walked inHashMaporder when the newands got their IDs.cargo test -p leonida-shader --lib bitcode::opt::testson the merge: 21 passed.opt.rson both sides. They build the new test's six-block module 64 times in one process. On main, the new IDs came out in 59 different orders, butModule::write()gave the same bytes in all 64 builds, whether afterchains()alone, afteroptimise(CHAINS | REUSE | DEAD)or afteroptimise(MODULE). On the merge: one order of the IDs in all 64 builds, and the same bytes in all three cases. So on this module, main's emitted bitcode was already the same from run to run. The pull request fixes the numbering insideModule.insts(what dumps and tests that print IDs see), as KelboLive's review on #2872 said. The body of #3059 says "instruction IDs", which is accurate. This is not a fix for output bytes or a shader cache key that changes between runs. Real programs were not checked.git statuswas clean:by_block.pop()after the empty check), sochains()rewrites one chain fewer. Killed by the new test (emitted ids in next block) and by the existingconjunctions_of_conditions_share_the_terms_they_start_with(stored values 4 instead of 2). The other 19bitcode::opt::testspass.HashMap(for (b, plans) in by_block.into_iter().collect::<HashMap<_, _>>()). This is the defect itself. Killed by the new test in 3 processes out of 3, each with a different order. The other 20bitcode::opt::testspass, so the new test is the only one that pins it.countersgoes back to aHashMap, with thesort_unstable()still removed, so the loop headers come in random order infind_exit_capsand in the phi completion. Whole lib: 421 / 0 / 5, it survives.find_exit_capswalks the headers in reverse (headers.into_iter().rev()). Whole lib: 421 / 0 / 5, it survives.So no test depends on the order in which loop headers claim an exit, and no test pins the
lower.rshalf. Reading the code:BTreeMap::keys()is ascending, which is what main'ssort_unstable()gave, andinto_values()fills each counter's own phi, so the order there does not reach the output either. Thelower.rschange is a cleanup with no change in behaviour, as KelboLive said.cargo clippy -p leonida-shader --all-targets, default and--features diagnostics, on main and on the merge: 6 warnings on each side, the same set (all invalu_tests.rs), none in the changed lines.cargo clippy --locked -p leonida-shader -- -D warnings(the command in the body) is clean on both sides.next_ifneeds each block's plans in body order. That holds, because they are collected by walking that same body just before, andtree.order(reverse postorder, the orderwritelays the blocks out) lists each reachable block once. The new IDs therefore follow the layout order.hostfeature.Verdict: PASS. The new test is red on
mainfor the stated reason and green on the merge, the suites and clippy matchmainwith one test more, and the carry keeps #2872's change as it was. Two notes for the maintainers: on the probe module, the fix is about the internal numbering, not the emitted bytes, and thelower.rshalf is a no-op cleanup that no test covers.Machine: Windows 11 Pro 26300, RTX 3090 24 GB, NVIDIA 621.40, Rust 1.98.1.
Imported from ubiquitarianism/leonida. Originally posted by lixonik on 2026-12-02T09:09:33Z.
Verified locally on Windows 10 x64 (rebased onto
maina917c54d6, PR head5d47d4f57):chains_emits_deterministic_instruction_ids_across_blocks):opt.rsfix (keeping only the new test againstmaina917c54d6): FAILED (rc=101, non-monotonic block emission order[[38, 39], [36, 37], [30, 31], [40, 41], [32, 33], [34, 35]]).#3059(5d47d4f57): PASSED (1 passed; 0 failed).cargo test -p leonida-shader --locked --lib emit::bitcode::opt::-- 21 passed, 0 failed.cargo clippy -p leonida-shader --locked --lib --tests-- exit0(0 warnings in touchedopt.rs/lower.rs).python -I scripts/check_no_game_data.py d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs d3d12/crates/leonida-shader/src/emit/lower.rs-- exit0.opt.rsremovesstd::collections::HashMapcompletely;chains()now preservestree.orderinby_block: Vec<(usize, Vec<(u32, Vec<Cond>)>)>and consumes each block's sorted plans via.into_iter().peekable()without per-blockHashMapallocation.lower.rschangesLower::countersfromHashMaptoBTreeMap, makingstd::mem::take(&mut self.counters).into_values()deterministic and removing the now-redundant.sort_unstable().Result: PASS (note: full
leonida-shader --libhits a pre-existing Win10 GPU test0xc0000005in untouchedemit::atomic_tests::heap_texture_atomic_widths, unrelated to this PR).AI-assisted: yes (Antigravity).
Imported from ubiquitarianism/leonida. Originally posted by imShangLi on 2026-12-02T10:18:55Z.
VERIFY-3059 — Linux, Fedora 45, Rust 1.98.1, no GPU device, no game files
Verdict: PASS. The change removes a real non-determinism from the translator's output, at the root cause (two standard
HashMaps whose iteration order decided the order of the emitted instructions), and the new test fails on the merge base and passes with the pull request. Nothing regressed.head
5d47d4f57("Merge remote-tracking branch 'origin/main' into carry/2872"), baseorigin/main=80910637f, merge basef37c4a87d. Two files, +76/−15:d3d12/crates/leonida-shader/src/emit/lower.rsandd3d12/crates/leonida-shader/src/emit/bitcode/opt.rs.This pull request is a carry of #2872 (kirigayakazima): the original was in conflict with
mainbecause both sides appended a test at the end of the same module inopt.rs, so this branch ismainmerged with #2872's head and keeps both tests. #2872 stays open until a maintainer decides which one lands.1. What it changes
Two maps whose iteration order decided the order of the emitted instructions:
lower.rs:591— the loop headers' iteration counters become aBTreeMapinstead of aHashMap. The order matters atlower.rs:15721: — the phi nodes are emitted in the map's iteration order, and a standardHashMap's order is different in every run (itsRandomStateseeds per map). The other use of the map (lower.rs:15407) collected the headers and sorted them, so it was already deterministic; the change replaces that sort with theBTreeMap's own order.opt.rs:1434—chains()grouped its per-block rewrite plans in aHashMap<usize, Vec<(u32, Vec<Cond>)>>and iterated it, so the blocks were rewritten in a random order and the new instructions landed in a random order. The plans are now grouped intree.order(the block order) in aVec, and the per-block lookup is apeekable()instead of aHashMap.The new test
chains_emits_deterministic_instruction_ids_across_blocksbuilds a module with six blocks in a reverse-ordered three-term conjunction, runschains()on it and asserts that the new instruction IDs advance monotonically in tree order, then runs the whole thing 16 times in one process and asserts that the block bodies and the written bytes (m.write()) are identical every time. Within one process twoHashMaps already iterate differently (RandomStateis seeded per map), so the base fails the test.2. The claims it makes, and which ones I checked
by_block: Vec<(usize, Vec<(u32, Vec<Cond>)>)>is filled while walkingfor &b in &tree.order(opt.rs:1434), and the later loop walks thatVec. True.counters: BTreeMap<usize, (V, Vec<(V, usize)>)>(lower.rs:591,lower.rs:2953), andlower.rs:15407no longer sorts the keys. True.m.write()over 16 runs, and it fails on the merge base (see below). True.9bb42034("d3d12-shader: make chains() and loop-counter lowering deterministic") is in the branch's history,main's own test at the end ofopt.rs(the 5-level 4-way diamond) is still there, and the new test follows it. True.opt.rssays "Which passes run isemit::shader_opt()(LEONIDA_SHADER_OPT), part of the translation and so of the shader cache's key", and the emitted instruction order is part of those bytes. A translation whose bytes differ per run cannot hit the cache. (The pull request does not measure the cache-hit effect; neither did I.)3. What the tests do here
python3 -I scripts/red_green.py 3059 --crate leonida-shader --work-dir /home/shangli/oc-workspace/gta6/rg-3059— verdict "red then green": the red side (the merge base plus only the pull request's test hunks) failsleonida_shader::emit::bitcode::opt::tests::chains_emits_deterministic_instruction_ids_across_blocks, the green side (the head) passes it, 252 tests pass on both sides, 0 regressions.cargo test -p leonida-shader --lib --lockedon the head: 253 passed, 0 failed, 2 ignored (2.6 s).4. Anything wrong in the change (with the file and line)
Nothing that changes the verdict. Two observations for the maintainer:
FxHashMap(rustc-hash) in several places and a standardHashMapin three (lds_exact.rs:74,lds_flags.rs:48,bitcode.rs:233): theFxHashMaps iterate in hash order, which is stable across runs of the same binary but would change if the hasher or the key types changed (a rebuild), and the three standard ones are only looked up, never iterated, so their order does not reach the output. The output is therefore stable across runs now; it is not, and was not, sorted.5. What I did not check
chains()or a loop counter (and how often the non-determinism was visible in the shipped shader library) is not measured — the finding is from the code, not from a corpus count.d3d12/rust-toolchain.toml. The author's Windows numbers (421 passed, 5 ignored) are theirs; the counts differ because of platform-gated tests.FxHashMapclaim above is from reading the code (opt.rs:150,opt.rs:1028,lower.rs:416and the three standard maps); I did not instrument a rebuild to see whether the emitted bytes change.leonida-shaderwas, because the change is confined to it.AI-assisted: the report was written with MiniMax M3.1 Flash (the pull request's own author says it was written with Claude Code).
Imported from ubiquitarianism/leonida. Originally posted by MoonEyes on 2026-12-02T10:38:00Z.
RUN (in game), #3059 head
5d47d4f57merged onto maina917c54d6withgit merge --no-ff, d3d12 layer rebuilt from that merge (diag profile). RTX 4060 8 GB, driver 610.88, Windows 11. Series S, -Resolution 1080, frame generation 2x, launcher default frame limit, same walking route as the #3062 runs, 330 s after reaching the world.For reference, the #3062 runs this morning on the same machine and route rendered 13.3 to 13.9 fps over the last 240 s; those had
LEONIDA_FG_LIMIT_FPSset explicitly, this one did not, so the fps are not a like-for-like comparison, only a check that nothing fell over. Three samples dropped to 1.0-4.3 fps, the last one at the moment the run was stopped.Verdict: PASS for the in-game gate (300 s or more in the world, no device loss). The long precompilation is consistent with a shader-compiler change invalidating the pipeline cache (ASSUMED, not checked by key).
Limits: one run; free system memory was low (median 0.6 GB); arrival in the world was driven by keys and not checked on pictures.
AI-assisted (Claude Code).
Imported from ubiquitarianism/leonida. Originally posted by MoonEyes on 2026-12-02T10:40:00Z.
Merging. Head
5d47d4f57merges cleanly withmain3a3c00822and does not force a rebase of #2566. Independent check on head5d47d4f57: enlight3d's red/green (new test red on main in 3/3 processes, green 21/21, leonida-shader 420 -> 421, comment 7339310843); in-game run of 330 s in the world on maina917c54d6+ this head, 0 device lost, 0 exceptions (comment 7342755519); CI green; merge approved in writing by Moon for this render-path PR. Merged by MoonEyes.AI-assisted (Claude Code).