Skip to content

shader/opt: extend Module::bounded() to zero-identity Add/Sub and budgeted acyclic Phi (D3D12-SHADER-BOUNDED-EXTENSIONS) - #2861

Open
djrolfes wants to merge 1 commit into
ProjectLeonida:mainfrom
djrolfes:djrolfes/shader-bounded-extensions
Open

djrolfes wants to merge 1 commit into
ProjectLeonida:mainfrom
djrolfes:djrolfes/shader-bounded-extensions

Conversation

@djrolfes

@djrolfes djrolfes commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

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 propagate f32 finite-magnitude bounds through two additional exact forms, directly improving both AMD rdna::LEGACY and 095af0c96's LEONIDA_LEGACY_PLAIN v_mul_legacy_f32 guard elision with zero behavioral change:

  1. Zero-identity Op::Bin(Bin::Add | Bin::Sub, a, b): When either operand is ±0.0 (self.float_k(...) == Some(0.0)), 0.0 ± x and x ± 0.0 preserve bounded(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 the 2^125 overflow cutoff (unbounded inputs still return None).
  2. Budgeted acyclic Op::Phi(inc): For non-empty phis (!inc.is_empty() && inc.len() <= 64), deduplicates repeated incoming values and returns Some(max_k bounded(val_k)?) when every incoming edge is bounded within the recursion depth. A shared visit budget (budget = 64 instruction visits in bounded_inner) guarantees O(1) worst-case time per bounded() query even on deep multi-way acyclic phi DAGs, while empty phis, phis with any unbounded edge, and cyclic loop phis (which exhaust depth or budget) conservatively return None.
  • Complementary to 095af0c96 (LEONIDA_LEGACY_PLAIN): Upstream 095af0c96 added LEONIDA_LEGACY_PLAIN (opt-in, off by default) calling self.s.m.bounded(a, 12) / bounded(b, 12) alongside the existing RDNA rdna::LEGACY path. This PR touches only Module::bounded() in bitcode/opt.rs and introduces no new switches or semantic changes.
  • Evidence classification: READ IN CODE (d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs:455–545 and lower.rs:5674–5720) + scripts/red_green.py verified red→green unit tests covering ±0.0 Add/Sub, near-2^125 negation, acyclic Phi, empty Phi, unbounded-edge Phi, incrementing/self-referential loop Phi, and wide 10-level 4-way Phi DAG visit-budget termination + MEASURED 300 s in-game gate on exact PR head ce91bce59.

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):
    red then green (2):
      leonida_shader::emit::bitcode::opt::tests::bounded_budget_caps_wide_phi_dag
      leonida_shader::emit::bitcode::opt::tests::bounded_tracks_zero_identity_and_acyclic_phi
    pass on both: 242
    verdict: red then green
    
  • Full cargo test --locked -p leonida-shader on PR head ce91bce59 (rebased onto cd73ddab7): 244 passed; 0 failed; 2 ignored (including source_hash_tests).
  • 300 s in-game gate (docs/game_gate.md) on exact PR head ce91bce59 (leonida.exe --profile play --features mimalloc,dlss,diagnostics, Series S + DLSS Quality 1280×720 → 1920×1080):
    • Verdict: PASS
    • In-world duration: 310.89 s (world_at_s = 82.27 s, >= 300 s required)
    • Frames (world + 60 s to stop): 3,458 presented frames (3,533 total world presents), 15.28 median FPS, 103.93 ms p95 frame time (15.42 end-window median FPS, 4,373.5 median draws/frame)
    • Longest present gap in world: 3.144 s (<= 10.0 s required)
    • Peak VRAM: 6,709 MiB (<= 7,400 MiB guard)
    • Stability: 0 device losses, 0 crashes/faults, 0 panics, 0 kernel NVRM: Xid errors

GPUs 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

  • Based on current main (cd73ddab7) and merges cleanly.
  • One topic; follow-up work goes in a new pull request.
  • No game data, keys or decryption (check_no_game_data.py clean).
  • A new translator rule is in the contract table of docs/design.md (n/a — sound Module::bounded() analysis extension, no new ISA rule).
  • Independent fresh reviewer agent audit completed (APPROVED).
  • 300 s in-game gate completed and PASSED on exact PR head (ce91bce59).

@Neutron-0

Copy link
Copy Markdown

Verified on Windows 11, and the control bites: the two new tests fail on today's main and pass with this.

main 7fbcd456e, 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):

cargo test -p leonida-shader --lib --locked -- bounded_
  on main, with the new tests alone:   FAILED
      emit::bitcode::opt::tests::bounded_tracks_zero_identity_and_acyclic_phi ... FAILED
          panicked at crates\leonida-shader\src\emit\bitcode\opt.rs:2925:9
      emit::bitcode::opt::tests::bounded_budget_caps_wide_phi_dag ... FAILED
          panicked at crates\leonida-shader\src\emit\bitcode\opt.rs:3001:9
      test result: FAILED. 1 passed; 2 failed; 0 ignored; 0 measured; 409 filtered out
  with this pull request:               ok. 3 passed; 0 failed; 0 ignored; 0 measured; 409 filtered out

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 acyclic Phi, with the empty phi, the unbounded edge and the cyclic phi still answering None.

PLACEHOLDER_SUITE

The whole crate with this pull request merged into main 7fbcd456e:

cargo test -p leonida-shader --lib --locked
  test result: FAILED. 403 passed; 4 failed; 5 ignored; 0 measured; 0 filtered out

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 on main itself 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 the PSV0 part'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.

@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.

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 +1 was over-conservative. The tests are genuinely red on the old arm (neg_sat and 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.0 and -0.0 - -0.0 flip the zero's sign and 0.0 + sNaN quiets it — fine for |v| <= 2^b, but exactly the distinction simplify() calls out. No counterexample exists where the arm returns Some for a non-finite value: float_k only accepts float constants or a 32-bit int bitcast, the IR has no vector type, and saturate is a dx.op.unary that is already exact under 0 ± x.

One thing I would change before merge: the budget. let mut budget = 64 is per bounded() query and shared across sibling branches, so it restricts acceptance: I built a 1023-node acyclic balanced Add tree over bounded constants and it returns Some(10.0) on the PR's parent and None here — a missed v_mul_legacy_f32 elision (falls back to compare+select, not a miscompile), which partially cancels this PR's own goal. 1 << depth or 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 --check flags 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.

@imShangLi

Copy link
Copy Markdown
Contributor

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 current main 85ec1d33, merge base cd73ddab, 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:

  • Zero identity for Add/Sub (opt.rs:485): if either operand is ±0.0, the bound of the other operand is returned as it is, instead of held(max(a, b) + 1.0). The + 1.0 was the slack for the rounding of a sum; a sum with zero has no rounding.
  • Acyclic 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 give None.
  • A shared visit budget (opt.rs:458,468): budget = 64 instruction visits per bounded() 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

$ python3 -I scripts/red_green.py pr2861 --no-fetch --crate leonida-shader --json
verdict: red then green
red_to_green: bounded_budget_caps_wide_phi_dag, bounded_tracks_zero_identity_and_acyclic_phi
regressions: []   fail_on_both: []   only_on_green: []   only_on_red: []
pass_on_both: 246

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:

form result bound returned sound?
0.0 + x x bounded(x) yes
x + 0.0 x (IEEE: x + (+0.0) is x, and for x = -0.0 it is +0.0, magnitude 0 either way) bounded(x) yes
0.0 - x -x bounded(x) yes, the magnitude is the same
x - 0.0 x bounded(x) yes

The ±0.0 case falls out of the comparison self.float_k(*a) == Some(0.0): -0.0 == 0.0 is 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_unbounded and add_unbounded → None), and it holds in the code.

It also removes a false None: x with a bound of 125.6 used to give held(125.6 + 1.0) → None (the sum is over 2^126, so the old rule could not prove it), while x + 0.0 is exactly x and is finite. The pull request's test has this case (neg_big → Some(125.0)).

4. The Phi rule is sound

  • The value of a join is one of its incoming values, so the maximum of their bounds is a bound ✓.
  • Any unbounded edge gives None for the whole join ✓ (conservative, and the test checks it).
  • An empty phi and a phi with more than 64 edges fall through to the catch-all → None ✓.
  • A cyclic phi (a loop's own value, or a self-referential one) recurses until the budget or the depth runs out and gives 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 same budget.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:

$ cargo test -p leonida-shader -- bounded_
test emit::bitcode::opt::tests::bounded_budget_caps_wide_phi_dag ... ok
test emit::bitcode::opt::tests::bounded_tracks_zero_identity_and_acyclic_phi ... ok

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 one Sub per 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):

case with the budget without it
the pull request's DAG (10 levels, 4 arms) None, 64 visits None, 12 visits — the depth limit stops it first
the same DAG at 5 levels None, 64 visits Some(0.0), 2,729 visits
a phi with 63 arms (one instruction each) Some(0.0), 64 visits Some(0.0), 64 visits
a phi with 64 arms None, 64 visits Some(0.0), 65 visits
a phi with 65 arms None, 1 visit None, 1 visit (the inc.len() <= 64 guard 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) into None — 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 None while a tree of 63 answers a bound; and the 65-arm phi is rejected by the inc.len() <= 64 guard rather than by the budget.

6. What the budget costs against main

main's bounded() 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 that main had: a tree of more than 63 instruction nodes now answers None where main answered a bound (as long as it was within 12 levels deep). A None is the conservative answer, so nothing becomes wrong — but it is the answer that decides whether the legacy multiply keeps its plain form:

// crates/leonida-shader/src/emit/lower.rs:5683, 5705, 5760
let (fa, fb) = (self.s.m.bounded(a, 12).is_some(), self.s.m.bounded(b, 12).is_some());
if a == b || fa && fb || not_zero(self, a) || not_zero(self, b) {
    return m;                      // the plain product
}
// … otherwise: compare both factors against zero and select

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

  • The 300-second in-game gate the pull request quotes (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.
  • The effect on the shader corpus — how much the emitted code grows or shrinks, and whether any real shader changes its legacy-multiply form. That needs the game's shaders, which I do not have. I measured the rule's thresholds on synthetic modules instead.
  • rdna::LEGACY and LEONIDA_LEGACY_PLAIN end to end. The unit tests cover bounded() 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_gives runs the programs on "hardware" and "warp"). I read the three call sites instead.
  • Windows, DXC and the driver. Everything above is Linux with no GPU device.
  • The other arm of the Phi rule I did not exercise: a phi whose edges come from blocks that are not its predecessors, and phis of integer type (those answer None by the fall-through, which I read rather than ran).

AI-assisted: MiniMax M3.1 Flash.

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.

4 participants