d3d12-shader: make chains() and loop-counter lowering deterministic #2872
No reviewers
No assignees
Labels
No labels
bug
dependencies
documentation
enhancement
missing claim
needs rebase
needs-triage
question
ready-for-agent
submodules
No project
No milestone
Dependencies
No dependencies set
Notifications
1 participant
Due date
No due date set.
Reference
leonida/mandy!2872
Loading…
Reference in a new issue
No description provided.
Delete branch "fix/d3d12-shader-deterministic-emit"
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?
Pull request successfully merged and closed
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)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.
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.
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.
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)
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)