d3d12-shader: make chains() and loop-counter lowering deterministic #2872
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/2872"
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 kirigayakazima on 2026-12-01T12:56:22Z.
Claimed in the coordination issue as: D3D12-SHADER-DETERMINISTIC-EMIT (https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7311583627)
What and why
Addresses @bobcatchris's finding (https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7298226194) on non-deterministic DXIL emission across runs:
d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs(Module::chains()), rewritten condition-chain plans were grouped intoby_block: std::collections::HashMap<usize, Vec<(u32, Vec<Cond>)>>and then iterated in randomizedRandomStatebucket order while allocating newV::Inst(x)IDs (self.insts.push(...)). Becausetree.orderalready visits each reachable block once andself.blocks[b].bodyis already in instruction order,chains()now buildsby_blockdirectly asVec<(usize, Vec<(u32, Vec<Cond>)>)>intree.orderand consumes per-block plans sequentially withpeekable().next_if(...), eliminating bothHashMaps inchains()(and removing the now-unusedstd::collections::HashMapimport).d3d12/crates/leonida-shader/src/emit/lower.rs,countersis switched fromHashMap<usize, (V, Vec<(V, usize)>)>toBTreeMapsostd::mem::take(&mut self.counters).into_values()in phi completion iterates in deterministic ascending IR-block order andfind_exit_caps()no longer needsheaders.sort_unstable()(reducinglower.rssize slightly).Tested
Verified locally (Windows 11, Rust 1.98.1, Windows SDK
dxil.dll, no game data):cargo test --locked -p leonida-shader --lib chains_emits_deterministic_instruction_ids_across_blockspanicked across blocks ([[40, 41], [30, 31], [36, 37], [32, 33], [34, 35], [38, 39]]).cargo test --locked -p leonida-shader --lib:410 passed; 0 failed; 5 ignored(includingchains_emits_deterministic_instruction_ids_across_blocks)cargo clippy --locked -p leonida-shader -- -D warnings: 0 warningspython -I scripts/check_no_game_data.py&git diff --check: cleanGPUs tested: n/a (translator unit tests only; validated against local Windows SDK
dxil.dll)AI-assisted: yes
Checklist
mainand merges cleanly (a conflicting pull request is labeledneeds rebase).docs/design.md, with how it was confirmed. (n/a: no new instruction rule)Imported from ubiquitarianism/leonida. Originally posted by merzleckeier on 2026-12-01T13:07:06Z.
Independent cross-process check of the optimizer regression from
9bb420346oned867d7b2. I put precisely the new six-blockchainstest on main with the old optimizer and built both with the Windows MSVC Rust target. The test failed in 3/3 fresh Wine 11.22 processes on main, each with a different non-monotonic assignment of new instruction IDs. The PR passed in 3/3 fresh processes, with identical emitted bytes across the 16 builds within each run. Its completeemit::bitcode::opt::testsfilter passed 19/19. This directly checks thechainschange on synthetic IR. The loop-counter change has no separate fixture in this run.AI-assisted with OpenAI Codex.
Imported from ubiquitarianism/leonida. Originally posted by KelboLive on 2026-12-01T13:28:10Z.
Review: COMMENTED
Nice catch — the outer
HashMapinchains()was the real bug: it decided the order in which newand/xorids were allocated, and replacing it with aVecfilled intree.ordergives a genuine total order. Reverting it reliably fails the new test (new instruction IDs must advance monotonically in tree order: [[32,33],[36,37],[40,41],[34,35],[38,39],[30,31]]), and my repeated-run probe is stable over 32 in-process runs and 8 independent threads × 8 (module bytes0x355c3da5eb8360f7, id hash0x888268bd2da29585).Two things to fix or state before merge:
Module::write()encodes relative value ids (bitcode.rs:572,:852) and per-block body order was already stable, so under the old code the output bytes were byte-identical; only the internalModule.instsnumbering (and dumps/tests that print ids) diverged. Worth saying in the commit so it doesn't read as a cache-key/output fix.countersHashMap→BTreeMapchange is inert. The only ordered consumer (find_exit_caps) already didheaders.sort_unstable()before this PR, andinto_values()(:15688) writes disjoint phi slots. I reverted it toHashMap+ sort and got identical DXIL (0xf9e31b0f5f6a0fb6), no failing test, and the same on a two-header program. Drop it, or label it as cleanup with no behaviour change.Minor: the
plans.next_if(|id| id == i)walk silently relies onplansbeing a subsequence of the body it is matched against — true today, but one line of comment would save the next refactor. Also note the branch's merge-base with main is stale (git diff main...prshows 211 files); the commit itself is the two files.Everything else checks out:
leaves.sort_by_keyinterms_ofis a stable sort on(born, neg)with a contains-onlyHashSet, and the otherHashMaps inlower.rsare get/insert/remove-only.Imported from ubiquitarianism/leonida. Originally posted by imShangLi on 2026-12-01T15:43:38Z.
VERIFY-2872 — Linux, Rust 1.98.1 (the pinned toolchain), no GPU device, no game files
Verdict: PASS. The repository's own red/green tool says the new test is red on
mainand green with the pull request.Head
9bb42034, base the currentmain88a9f133, merge base2d4f316b, 1 commit, 2 files, +76/−15:d3d12/crates/leonida-shader/src/emit/bitcode/opt.rsandd3d12/crates/leonida-shader/src/emit/lower.rs.1. The change
Two places where a
HashMapdecided an order:opt.rs, inchains()— the rewrites were collected per block into aHashMap<usize, Vec<(u32, Vec<Cond>)>>and then walked in the map's iteration order. Rust'sHashMapuses a randomly seeded hasher, so that order differs between processes; the pull request keeps the blocks in aVecin tree order and walks the plans of a block with a peekable iterator instead ofplans.remove(&i).lower.rs, in the loop-counter lowering —counters: HashMap<usize, (V, Vec<(V, usize)>)>becomes aBTreeMap, and theheaders.sort_unstable()that followed thekeys()call is dropped because the keys are already in order.Both are the same defect: an order that is not fixed, in a stage whose result is hashed into the shader cache's key.
2. Red and green
python -I scripts/red_green.py pr2872 --crate leonida-shader(the repository's own tool: red is the base with only this pull request's test hunks, green is the base with the pull request merged):On the red side the new test fails; on the green side the crate is green.
3. What the new test checks
chains_emits_deterministic_instruction_ids_across_blocksbuilds a module with six blocks, each holding a three-term conjunction, runschains(), and then checks two things:The second half is the part that catches the
HashMap: each run builds fresh maps, and a randomly seededHashMapgives a different iteration order each time, so the 16 runs would disagree.4. It does not collide with #2800
#2800 also changes
chains()inopt.rs(it makes the canonical test accept a commutativeand). I merged both onto today'smainand ran the crate:No conflict, and neither pull request's test breaks the other's.
5. What I did not check
opt.rssays the optimisation flags are "part of the translation and so of the shader cache's key").lower.rschange. I checked thatBTreeMap'skeys()is sorted, so droppingsort_unstable()keeps the same order, and that the type change is the only use of the field. I did not trace every reader ofcounters.leonida-gpu,leonida-hleandleonida-loaderdo not build on Linux for reasons that predate this pull request (upstream: "The crates are Windows-only today … Linux follows #2577"), so I ranleonida-shaderon its own.HashMaps in the shader crate whose iteration order reaches the output. I looked at the two this pull request touches; I did not audit the crate for others.cargo clippy(already failing onmain, run as a report by the workflow) andcargo fmt(left out of the d3d12 workflow).AI-assisted: MiniMax M3.1 Flash.
Imported from ubiquitarianism/leonida. Originally posted by DadaCap on 2026-12-01T16:15:02Z.
Independent red/green on Windows 11 (RTX 5080, NVIDIA 621.24), head
9bb420346merged into main0ff8a532f, withpython -I scripts/red_green.py 2872:leonida_shader::emit::bitcode::opt::tests::chains_emits_deterministic_instruction_ids_across_blocksfails on main with only the PR's tests and passes with the PR;leonida-shader).No in-game run from me. AI-assisted (Claude Code), posted for DadaCap.
Imported from ubiquitarianism/leonida. Originally posted by MoonEyes on 2026-12-01T22:07:26Z.
main moved and this PR now conflicts in
d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs: both sides appended a test at the end of the same module. I resolved it by keeping both tests (merge commitaa13e59fbonMoonEyes/leonidabranchcarry/2872, based on mainc4ca57615;cargo test -p leonida-shader --libon the two conflicting tests plusbounded_budget_caps_wide_phi_dag: 4 passed).Please rebase or merge main into this branch yourself. If it is still conflicting in 6 hours I will open a carry PR that keeps your commit. Nothing else changes in your diff.
AI-assisted (Claude Code)
Imported from ubiquitarianism/leonida. Originally posted by MoonEyes on 2026-12-02T06:44:33Z.
As said above, this PR still conflicts with
mainand has not moved. I opened #3059, which ismainmerged with this head: your commit is kept, both tests are kept. This PR stays open until a maintainer decides. If you rebase it yourself, say so and I will close #3059.AI-assisted (Claude Code)