shader/opt: extend Module::bounded() to zero-identity Add/Sub and budgeted acyclic Phi (D3D12-SHADER-BOUNDED-EXTENSIONS) #2861
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/2861"
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 djrolfes on 2026-12-01T10:24:53Z.
Claimed in the coordination issue as:
D3D12-SHADER-BOUNDED-EXTENSIONS(claim comment)What and why
Extend
Module::bounded()(d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs) to soundly propagatef32finite-magnitude bounds through two additional exact forms, directly improving both AMDrdna::LEGACYand095af0c96'sLEONIDA_LEGACY_PLAINv_mul_legacy_f32guard elision with zero behavioral change:Op::Bin(Bin::Add | Bin::Sub, a, b): When either operand is±0.0(self.float_k(...) == Some(0.0)),0.0 ± xandx ± 0.0preservebounded(x)directly instead of adding+ 1.0. In particular, RDNA2 float negation lowers to-0.0 - x, so this avoids doubling the magnitude bound or losing the proof at the2^125overflow cutoff (unbounded inputs still returnNone).Op::Phi(inc): For non-empty phis (!inc.is_empty() && inc.len() <= 64), deduplicates repeated incoming values and returnsSome(max_k bounded(val_k)?)when every incoming edge is bounded within the recursion depth. A shared visit budget (budget = 64instruction visits inbounded_inner) guaranteesO(1)worst-case time perbounded()query even on deep multi-way acyclic phi DAGs, while empty phis, phis with any unbounded edge, and cyclic loop phis (which exhaustdepthorbudget) conservatively returnNone.095af0c96(LEONIDA_LEGACY_PLAIN): Upstream095af0c96addedLEONIDA_LEGACY_PLAIN(opt-in, off by default) callingself.s.m.bounded(a, 12)/bounded(b, 12)alongside the existing RDNArdna::LEGACYpath. This PR touches onlyModule::bounded()inbitcode/opt.rsand introduces no new switches or semantic changes.d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs:455–545andlower.rs:5674–5720) +scripts/red_green.pyverified red→green unit tests covering±0.0Add/Sub, near-2^125negation, acyclicPhi, emptyPhi, unbounded-edgePhi, incrementing/self-referential loopPhi, and wide 10-level 4-wayPhiDAG visit-budget termination + MEASURED 300 s in-game gate on exact PR headce91bce59.Tested
python3 -I scripts/check_no_game_data.py d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs→ exit 0.python3 -I scripts/red_green.py pr/shader-bounded-extensions --base origin/main --no-fetch --no-python(native Linux):cargo test --locked -p leonida-shaderon PR headce91bce59(rebased ontocd73ddab7):244 passed; 0 failed; 2 ignored(includingsource_hash_tests).docs/game_gate.md) on exact PR headce91bce59(leonida.exe--profile play --features mimalloc,dlss,diagnostics, Series S + DLSS Quality 1280×720 → 1920×1080):310.89 s(world_at_s = 82.27 s,>= 300 srequired)world + 60 sto stop):3,458presented frames (3,533total world presents),15.28median FPS,103.93 msp95 frame time (15.42end-window median FPS,4,373.5median draws/frame)3.144 s(<= 10.0 srequired)6,709 MiB(<= 7,400 MiBguard)0device losses,0crashes/faults,0panics,0kernelNVRM: XiderrorsGPUs tested: NVIDIA GeForce RTX 3070 Ti 8 GB, driver 620.73.04, Arch Linux (Wine 11.22 + VKD3D-Proton 3.2.0).
AI-assisted: yes (authored by Gemini 4 Neon; audited and approved in a separate independent review pass by Gemini 4 Neon).
Checklist
main(cd73ddab7) and merges cleanly.check_no_game_data.pyclean).docs/design.md(n/a — soundModule::bounded()analysis extension, no new ISA rule).ce91bce59).Imported from ubiquitarianism/leonida. Originally posted by Neutron-0 on 2026-12-01T11:15:13Z.
Verified on Windows 11, and the control bites: the two new tests fail on today's
mainand pass with this.main7fbcd456e, cargo 1.98.1. The control was this pull request's own tests with the change reverted (the diff's first hunk is the change, the second the tests, so the tests can be applied alone):So both rules are exercised by the change and not by the tests alone: the zero-identity
Add/Sub(including the RDNA2 negation form-0.0 - x) and the budgeted acyclicPhi, with the empty phi, the unbounded edge and the cyclic phi still answeringNone.PLACEHOLDER_SUITE
The whole crate with this pull request merged into
main7fbcd456e:The four failures are the tests that run the DXIL validator (
emit::rect::tests::rectangles_are_drawn_whole,emit::rect::tests::the_rectangle_stage_is_a_geometry_shader,emit::barycentric_tests::a_masked_pixel_program_reads_the_position_where_the_vertex_program_writes_it,emit::barycentric_tests::first_half_values_render_on_hardware_and_warp), and they fail onmainitself with "Container part 'Pipeline State Validation' does not match expected for module" - a separate defect, fixed by #2864 (one copy of a semantic's name per element in thePSV0part's name table). With that one merged as well, the crate is green (406 tests OK, 0 failed on the pull request's head of #2864).So this pull request adds two tests and changes no other result.
One note on the in-game gate: it is the right kind of evidence for this change, since a wider bound only ever removes a guard, and the gate shows the frame times and the stability are unchanged. What a CPU-only check cannot do is count the guards that are no longer emitted over the title's own shaders, so the "improves the guard elision" half of the claim stays unmeasured here - the unit tests show the bound is now known where it was not, not how often the title's shaders reach it.
Imported from ubiquitarianism/leonida. Originally posted by KelboLive on 2026-12-01T13:53:22Z.
Review: COMMENTED
Sound direction, and the zero case is the right fix for RDNA's
-0.0 - x— it only fires when the non-zero side already has a bound, so nothing new is asserted finite, and the old+1was over-conservative. The tests are genuinely red on the old arm (neg_satand the two-level phi diamond both fail), so the extension is pinned.Worth stating in the commit: this is magnitude-identity, not bit-identity.
+0.0 + -0.0and-0.0 - -0.0flip the zero's sign and0.0 + sNaNquiets it — fine for|v| <= 2^b, but exactly the distinctionsimplify()calls out. No counterexample exists where the arm returnsSomefor a non-finite value:float_konly accepts float constants or a 32-bit int bitcast, the IR has no vector type, andsaturateis adx.op.unarythat is already exact under0 ± x.One thing I would change before merge: the budget.
let mut budget = 64is perbounded()query and shared across sibling branches, so it restricts acceptance: I built a 1023-node acyclic balancedAddtree over bounded constants and it returnsSome(10.0)on the PR's parent andNonehere — a missedv_mul_legacy_f32elision (falls back to compare+select, not a miscompile), which partially cancels this PR's own goal.1 << depthor memoising(v, depth)per query would cap the phi blow-up without dropping those proofs. The 300 s gate cannot see this because it has no elision count.Minor:
rustfmt --checkflags the newly joined over-width arms (:479,:495,:525); the base file already fails elsewhere and the workspace fmt job is launcher-only, so it is cosmetic.Imported from ubiquitarianism/leonida. Originally posted by imShangLi on 2026-12-01T17:00:22Z.
VERIFY-2861 — Linux, Fedora 45, Rust 1.98.1 (the pinned toolchain), no GPU device, no game files
Verdict: PASS. The repository's own red/green verifier says red then green, the two rules the pull request adds are sound for the quantity
bounded()computes (a bound on the magnitude of a float), and the change only makes the analysis more precise in the one place where it could have made it unsound. One thing the pull request's tests do not show: the visit budget is not what the new test named after it checks — at the size that test builds, the pre-existing depth limit already decides the answer.Head
ce91bce5, base the currentmain85ec1d33, merge basecd73ddab, 1 commit, 1 file, +184/−12:d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs.1. What it changes
Module::bounded()(opt.rs:457) answers "is this float a finite number, and if so, what power of two bounds its magnitude". The pull request extends it in two ways and adds a third thing that bounds the work:Add/Sub(opt.rs:485): if either operand is±0.0, the bound of the other operand is returned as it is, instead ofheld(max(a, b) + 1.0). The+ 1.0was the slack for the rounding of a sum; a sum with zero has no rounding.Phi(opt.rs:501): the bound of a join is the maximum of the bounds of its incoming values; an empty phi, a phi with more than 64 incoming edges, a phi with any unbounded edge, and a cyclic phi all giveNone.opt.rs:458,468):budget = 64instruction visits perbounded()call, decremented on the way into every instruction, so a query costs O(1) no matter how wide the graph is.2. The repository's own red/green verifier says red then green
Both new tests fail on the base and pass on the head, and nothing else moves.
3. The zero identity is sound for a magnitude bound
bounded()'s contract is about magnitude ("a power of two its magnitude does not pass"), so a sign flip is free but a change of magnitude is not. Checking the four forms the pull request relies on:0.0 + xxbounded(x)x + 0.0x(IEEE:x + (+0.0)isx, and forx = -0.0it is+0.0, magnitude 0 either way)bounded(x)0.0 - x-xbounded(x)x - 0.0xbounded(x)The
±0.0case falls out of the comparisonself.float_k(*a) == Some(0.0):-0.0 == 0.0is true in IEEE, so both zeros are caught by one test — which is what the pull request's body says.The important direction is the one that could have been unsound: an unbounded operand still gives
None, because the rule returns the bound of the other operand, not of the zero. The pull request's own test checks this (neg_unboundedandadd_unbounded→None), and it holds in the code.It also removes a false
None:xwith a bound of 125.6 used to giveheld(125.6 + 1.0)→None(the sum is over2^126, so the old rule could not prove it), whilex + 0.0is exactlyxand is finite. The pull request's test has this case (neg_big→Some(125.0)).4. The Phi rule is sound
Nonefor the whole join ✓ (conservative, and the test checks it).None✓.None✓ — no infinite recursion, because the budget is decremented on the way into every instruction (opt.rs:468), before the recursion.The budget also matches an idiom already in the same file:
terms_of(opt.rs:1253,1264) uses the samebudget.checked_sub(1)?shape with a budget of 256.5. The new tests do not discriminate the visit budget
This is the one thing I would change in the pull request. I took the budget away —
budget = u32::MAX— and both new tests still pass:The reason is the depth limit, which is older than this pull request:
bounded(v, 12)walks at most 12 levels, and the DAG the test builds is 10 levels of phi plus oneSubper arm — two depth per level — so the depth limit is reached before the budget matters.I measured the visits (I counted them with a temporary counter, and reverted it afterwards):
None, 64 visitsNone, 12 visits — the depth limit stops it firstNone, 64 visitsSome(0.0), 2,729 visitsSome(0.0), 64 visitsSome(0.0), 64 visitsNone, 64 visitsSome(0.0), 65 visitsNone, 1 visitNone, 1 visit (theinc.len() <= 64guard rejects it before any work)So the budget is real and useful — it is what stops the 5-level DAG at 64 visits instead of 2,729, and it is what turns a 64-arm phi from
Some(0.0)intoNone— but the test that carries its name would only notice its absence at 5 levels, not at the 10 it builds. A 5-level version of the same DAG in that test would make it discriminating; at 10 levels it is not.Two more numbers worth having: the budget allows exactly 64 instruction visits per query (constants are free — they are answered before the budget is touched), so a tree of 64 instruction nodes answers
Nonewhile a tree of 63 answers a bound; and the 65-arm phi is rejected by theinc.len() <= 64guard rather than by the budget.6. What the budget costs against
mainmain'sbounded()has no budget and no phi rule. The phi rule only ever adds bounds. The budget, on the other hand, can take away a bound thatmainhad: a tree of more than 63 instruction nodes now answersNonewheremainanswered a bound (as long as it was within 12 levels deep). ANoneis the conservative answer, so nothing becomes wrong — but it is the answer that decides whether the legacy multiply keeps its plain form:A lost bound therefore means the spelled-out form instead of the plain product — more instructions, same result. I did not measure how often that happens, because the only inputs that would show it are the game's shaders (§7).
7. What I did not check
310.89 s in-world). That needs the game files and a GPU; I have neither. My verdict is about the analysis, not about the frame time.rdna::LEGACYandLEONIDA_LEGACY_PLAINend to end. The unit tests coverbounded()only; the lowering that consumes it is exercised by tests that need a GPU (valu_tests.rs::legacy_plain_forms_give_what_the_spelled_out_one_givesruns the programs on "hardware" and "warp"). I read the three call sites instead.Phirule I did not exercise: a phi whose edges come from blocks that are not its predecessors, and phis of integer type (those answerNoneby the fall-through, which I read rather than ran).AI-assisted: MiniMax M3.1 Flash.
Imported from ubiquitarianism/leonida. Originally posted by OreoFR on 2026-12-01T20:34:26Z.
Merging. Head
ce91bce59merges cleanly with main66c79286f. Claim: D3D12-SHADER-BOUNDED-EXTENSIONS (https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7305584573). Red/green: Neutron-0 (Windows 11, the two new tests fail on main and pass with this), imShangLi (Linux, PASS), KelboLive review on this head. I ran: the five PRs #2860, #2861, #2862, #2824 and #2873 merged together onto mainab374c7d5(main has since gained only #2935, a CI workflow change), with the shader (418 passed, 0 failed), gpu (644/0) and hle (247/0) cargo tests. In-game run: RTX 4070 Laptop 8 GB, NVIDIA 621.40, a cold start to the world then a 330 s warm walking run, 0 device lost, no panic. CI: green on head and main. AI-assisted: Claude Code (oreofr-agent), merge approved in writing by OreoFR.Imported from ubiquitarianism/leonida. Originally posted by enlight3d on 2026-12-01T23:07:17Z.
RUN, posted after the merge: the review points below are for a follow-up. (independent run on Windows, #2861 head
ce91bce59, merged locally intomain0ff8a532fwithgit merge --no-ff, no conflicts. CI on the head: change-scope, check, linux-python-and-viewer, no-game-data and semantic-tests all pass.)Commands, in
d3d12/, target x86_64-pc-windows-gnu (the host this machine's rustup selects; CI builds x86_64-pc-windows-msvc), toolchain 1.98.1, all with--locked, at low priority,RUST_TEST_THREADS=8:cargo test -p leonida-shader --no-fail-fast: main 414 passed / 0 failed / 5 ignored; merge 416 / 0 / 5 (the 2 new tests). Some of these tests run on the GPU, here an RTX 3090;host_forms_give_what_the_spelled_out_ones_givepasses on both sides.cargo test -p leonida-shader --no-fail-fast --features diagnostics: main 414 / 0 / 5; merge 416 / 0 / 5.opt.rswith this pull request's two tests added and its production hunk left out.cargo test -p leonida-shader --lib bitcode::opt::tests::bounded: both fail.bounded_tracks_zero_identity_and_acyclic_phion the first new-form assertion (-0.0 - saturate(x)), leftSome(1.0), rightSome(0.0);bounded_budget_caps_wide_phi_dagon the two-level diamond, leftNone, rightSome(0.0).bitcode::opt::tests(and with the whole crate where noted):None): both new tests fail (phi_badgivesSome(0.0), the DAGSome(-inf)). TheNoneon an unbounded edge is pinned.*budget = budget.checked_sub(1)?;line deleted): the 20 module tests pass; the whole-crate run was stopped by a game start after 240 of the 421 tests (all passing) and could not be redone here, the card being busy with game runs. The budget test cannot catch it: with depth 12 and two instructions per level (a phi and a subtraction), the walk runs out of depth after 6 of the 10 levels whatever the budget, so its finalNonecomes from the depth limit (at most 4^6 = 4,096 paths, which is quick). Its comment also says "5-level" for a 10-level loop.self.float_k(*a).is_some()and the same forb, in place of== Some(0.0)). This is unsound:4.0 + saturate(x)would get the bound ofsaturate(x), 2^0, where 2^3 is needed. The 20 module tests pass; whole crate: 416 passed / 0 failed / 5 ignored, it survives. Every addition or subtraction the new tests ask about has a zero operand, except the loop'sphi + 1.0, which ends in the depth limit either way. A case such asbounded(4.0 + saturate(x)) == Some(3.0)would pin the "zero" in zero identity.opt.rson both sides;cargo test -p leonida-shader --lib zz_probe): the bound of a sum of 32saturateresults (a balanced tree of adds, 63 instructions) isSome(5.0)on main and on the merge; for 64 of them (127 instructions) it isSome(6.0)on main andNoneon the merge. The 64-visit budget makesbounded()give up on factors of more than 64 instructions that main proved, and such a legacy product gets its guard back. That is the safe direction (more guards, never fewer), but it is a change of output against main, where the body says "zero behavioral change". How often a factor in the real programs passes 64 instructions was not measured.git statusclean),cargo test -p leonida-shader --lib bitcode::opt::tests: 20 passed.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.python -I tools/d3d12_switches.py --check d3d12/docs/switches.mdis clean on the merge (no switch added).x + 0,0 + x,x - 0and0 - xhave the magnitude ofx, and the rule only applies whenxalready has a bound. A phi is one of its incoming values, so the largest bound covers it; on a cycle the walk only returnsSomewhen the back edge is bounded without going through the phi again (a saturate, say), otherwise depth or budget end it inNone.bounded()is asked only bylegacy_mulandlegacy_mad, and only matters withrdna::LEGACYwithoutZERO_SIGN(an AMD RDNA host,LEONIDA_RDNA_FLOAT) or withLEONIDA_LEGACY_PLAINwhereLEGACYis off. On NVIDIA the defaultLEONIDA_HOST_FLOAThasZERO_SIGN:legacy_multhen never readsfa/fbandlegacy_madskips that path. So with default switches the change does nothing on an NVIDIA card: neither the body's in-game gate (RTX 3070 Ti) nor this card can show it; an RDNA host can.Machine: Windows 11 Pro 26300, i9-13900K, 64 GB, RTX 3090 24 GB, NVIDIA 621.40, Rust 1.98.1.