Skip to content

d3d12-shader: make chains() and loop-counter lowering deterministic - #2872

Open
kirigayakazima wants to merge 1 commit into
ProjectLeonida:mainfrom
kirigayakazima:fix/d3d12-shader-deterministic-emit
Open

kirigayakazima wants to merge 1 commit into
ProjectLeonida:mainfrom
kirigayakazima:fix/d3d12-shader-deterministic-emit

Conversation

@kirigayakazima

Copy link
Copy Markdown
Contributor

Claimed in the coordination issue as: D3D12-SHADER-DETERMINISTIC-EMIT (#2570 (comment))

What and why

Addresses @bobcatchris's finding (#2570 (comment)) on non-deterministic DXIL emission across runs:

  1. In d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs (Module::chains()), rewritten condition-chain plans were grouped into by_block: std::collections::HashMap<usize, Vec<(u32, Vec<Cond>)>> and then iterated in randomized RandomState bucket order while allocating new V::Inst(x) IDs (self.insts.push(...)). Because tree.order already visits each reachable block once and self.blocks[b].body is already in instruction order, chains() now builds by_block directly as Vec<(usize, Vec<(u32, Vec<Cond>)>)> in tree.order and consumes per-block plans sequentially with peekable().next_if(...), eliminating both HashMaps in chains() (and removing the now-unused std::collections::HashMap import).
  2. In d3d12/crates/leonida-shader/src/emit/lower.rs, counters is switched from HashMap<usize, (V, Vec<(V, usize)>)> to BTreeMap so std::mem::take(&mut self.counters).into_values() in phi completion iterates in deterministic ascending IR-block order and find_exit_caps() no longer needs headers.sort_unstable() (reducing lower.rs size slightly).

Tested

Verified locally (Windows 11, Rust 1.98.1, Windows SDK dxil.dll, no game data):

  • Red before fix: cargo test --locked -p leonida-shader --lib chains_emits_deterministic_instruction_ids_across_blocks panicked across blocks ([[40, 41], [30, 31], [36, 37], [32, 33], [34, 35], [38, 39]]).
  • Green after fix:
    • cargo test --locked -p leonida-shader --lib: 410 passed; 0 failed; 5 ignored (including chains_emits_deterministic_instruction_ids_across_blocks)
    • cargo clippy --locked -p leonida-shader -- -D warnings: 0 warnings
    • python -I scripts/check_no_game_data.py & git diff --check: clean

GPUs tested: n/a (translator unit tests only; validated against local Windows SDK dxil.dll)

AI-assisted: yes

Checklist

  • Based on current main and merges cleanly (a conflicting pull request is labeled needs rebase).
  • One topic; follow-up work goes in a new pull request.
  • No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here.
  • A new translator rule is in the contract table of docs/design.md, with how it was confirmed. (n/a: no new instruction rule)

@merzleckeier

Copy link
Copy Markdown
Contributor

Independent cross-process check of the optimizer regression from 9bb420346 on ed867d7b2. I put precisely the new six-block chains test 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 complete emit::bitcode::opt::tests filter passed 19/19. This directly checks the chains change on synthetic IR. The loop-counter change has no separate fixture in this run.

AI-assisted with OpenAI Codex.

@KelboLive KelboLive left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice catch — the outer HashMap in chains() was the real bug: it decided the order in which new and/xor ids were allocated, and replacing it with a Vec filled in tree.order gives 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 bytes 0x355c3da5eb8360f7, id hash 0x888268bd2da29585).

Two things to fix or state before merge:

  1. The emitted DXIL was already deterministic — 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 internal Module.insts numbering (and dumps/tests that print ids) diverged. Worth saying in the commit so it doesn't read as a cache-key/output fix.
  2. The counters HashMap→BTreeMap change is inert. The only ordered consumer (find_exit_caps) already did headers.sort_unstable() before this PR, and into_values() (:15688) writes disjoint phi slots. I reverted it to HashMap + 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 on plans being 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...pr shows 211 files); the commit itself is the two files.

Everything else checks out: leaves.sort_by_key in terms_of is a stable sort on (born, neg) with a contains-only HashSet, and the other HashMaps in lower.rs are get/insert/remove-only.

@imShangLi

Copy link
Copy Markdown
Contributor

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 main and green with the pull request.

Head 9bb42034, base the current main 88a9f133, merge base 2d4f316b, 1 commit, 2 files, +76/−15: d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs and d3d12/crates/leonida-shader/src/emit/lower.rs.

1. The change

Two places where a HashMap decided an order:

opt.rs, in chains() — the rewrites were collected per block into a HashMap<usize, Vec<(u32, Vec<Cond>)>> and then walked in the map's iteration order. Rust's HashMap uses a randomly seeded hasher, so that order differs between processes; the pull request keeps the blocks in a Vec in tree order and walks the plans of a block with a peekable iterator instead of plans.remove(&i).

lower.rs, in the loop-counter lowering — counters: HashMap<usize, (V, Vec<(V, usize)>)> becomes a BTreeMap, and the headers.sort_unstable() that followed the keys() 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):

verdict: "red then green"
red_to_green: leonida_shader::emit::bitcode::opt::tests::chains_emits_deterministic_instruction_ids_across_blocks
regressions:  []
fail_on_both: []
pass_on_both: 246

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_blocks builds a module with six blocks, each holding a three-term conjunction, runs chains(), and then checks two things:

  • the newly emitted instruction IDs advance monotonically in tree order — the maximum of one block's new IDs is below the minimum of the next block's, so block n's rewrite is numbered before block n+1's, whatever order the blocks were visited in;
  • running the whole thing 16 times gives the same result each time.

The second half is the part that catches the HashMap: each run builds fresh maps, and a randomly seeded HashMap gives a different iteration order each time, so the 16 runs would disagree.

4. It does not collide with #2800

#2800 also changes chains() in opt.rs (it makes the canonical test accept a commutative and). I merged both onto today's main and ran the crate:

test result: ok. 249 passed; 0 failed; 2 ignored

No conflict, and neither pull request's test breaks the other's.

5. What I did not check

  • The translation of a real shader, and the cache. The consequence of a varying instruction numbering is a varying shader cache key, which costs a re-translation; I did not measure that, and I did not translate a game shader (they are not in the repository, and the pull request's own note in opt.rs says the optimisation flags are "part of the translation and so of the shader cache's key").
  • The whole lower.rs change. I checked that BTreeMap's keys() is sorted, so dropping sort_unstable() keeps the same order, and that the type change is the only use of the field. I did not trace every reader of counters.
  • The other crates in the workspace — leonida-gpu, leonida-hle and leonida-loader do not build on Linux for reasons that predate this pull request (upstream: "The crates are Windows-only today … Linux follows Linux: build leonida.exe and run it under Proton or Wine #2577"), so I ran leonida-shader on its own.
  • Whether there are other 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 on main, run as a report by the workflow) and cargo fmt (left out of the d3d12 workflow).

AI-assisted: MiniMax M3.1 Flash.

@DadaCap

DadaCap commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

Independent red/green on Windows 11 (RTX 5080, NVIDIA 621.24), head 9bb420346 merged into main 0ff8a532f, with python -I scripts/red_green.py 2872:

  • red then green (1): leonida_shader::emit::bitcode::opt::tests::chains_emits_deterministic_instruction_ids_across_blocks fails on main with only the PR's tests and passes with the PR;
  • pass on both: 414 (leonida-shader).

No in-game run from me. AI-assisted (Claude Code), posted for DadaCap.

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.

5 participants