Skip to content

D3D12-SHADER-BDD-UNIQUE-COMPACT: open-addressing unique table for the BDD nodes (-3 % wall, DXIL identical) - #2788

Merged
OreoFR merged 1 commit into
ProjectLeonida:mainfrom
bobcatchris:perf/d3d12-bdd-unique-compact
Dec 1, 2026
Merged

OreoFR merged 1 commit into
ProjectLeonida:mainfrom
bobcatchris:perf/d3d12-bdd-unique-compact

Conversation

@bobcatchris

Copy link
Copy Markdown
Contributor

What

Bools (the BDD behind the lane-mask structuriser in leonida-shader/src/structure.rs) keeps its unique table in a HashMap<(u32, Bool, Bool), Bool>. That is about 17 bytes a slot at 44-87 % load, 19-39 bytes per node, and it was 11 % of the CPU time of the 500 slowest programs (insert_no_grow 8.8 % plus reserve_rehash 2.3 % of their samples). Those programs are the ones whose CPU time scales worst with threads (2.38x CPU time at 16 threads against 1.48x for the median program), because their diagrams (about 1 M nodes, 46 % live at the end) do not fit the cache.

This replaces the map with open addressing over node numbers: a 4-byte slot (21-bit node number plus an 11-bit tag), load at most 1/2, linear probing, and equality checked on the node itself (nodes[node] == triple), so a tag collision cannot return a wrong node. Nodes are made in the same order as before, so nothing downstream sees a difference. MAX_NODES stays 1 << 21 and a compile-time assert ties it to the slot layout.

Claim: D3D12-SHADER-BDD-UNIQUE-COMPACT (coordination issue #2570). Touches Bools::new, Bools::mk and one test; no overlap with an open pull request (#2750 is in other files of the same crate).

Measured

Full-archive leonida translate on the retail shader archive, release build with diagnostics,mimalloc, 16 threads, Ryzen 7 7800X3D, 3 alternating runs of each, main at d8ca182 as the baseline:

wall user CPU
main 38.7 / 38.7 / 38.9 s 510.2 / 514.0 / 515.4 s
this branch 38.1 / 37.4 / 37.2 s 505.8 / 502.9 / 502.5 s

That is -3.1 % wall and -1.9 % CPU on mean values. On the 500 slowest programs alone (same method, 3 runs each): wall 15.2 / 14.8 / 14.8 s -> 13.9 / 13.8 / 13.8 s (-7.4 %), user CPU 201.5 / 199.9 / 200.8 s -> 189.4 / 189.4 / 188.1 s (-5.8 %).

DXIL output is identical. The blake3 of the DXIL of all 25689 programs (15799 distinct) is the same as main's in every run, full archive and heavy set (a scratch patch that writes the hashes; it is not part of this pull request).

Tests

  • New the_unique_table_gives_a_triple_its_node_again_through_every_growth: 400 000 random nodes over 40 variables while the table grows from 1 024 slots to at least 262 144, each checked against a HashMap: the same triple gives the same node, a new triple the next number, nodes[got] == triple, then every triple is asked again and no node is made, and a triple over a variable nobody used is new. Negative control: replacing the nodes[node] == triple comparison with true makes it fail.
  • cargo test -p leonida-shader --release: 401 passed, 0 failed, 5 ignored.
  • rustfmt --edition 2024 --check on structure.rs: the nine diffs it reports were there before and are not in this change; clippy reports nothing in it.
  • check_no_game_data.py on the changed file: clean.

AI-assisted: Claude Sonnet 5.5

`Bools::unique` was a HashMap<(u32, Bool, Bool), Bool>: 17 bytes a slot at 44-87 %
load and 19-39 bytes per node, and 11 % of the CPU time of the 500 slowest programs
(the diagrams there hold about 1 M nodes and do not fit the cache).

Replace it with open addressing over node numbers: a 4-byte slot (21-bit node
number, 11-bit tag), load at most 1/2, linear probing, equality checked on the node
itself. Nodes are made in the same order, so the structuriser's output is the same.

The new test makes 400 000 random nodes over 40 variables, with the table growing
from 1 024 slots to at least 262 144, and checks every one against a HashMap: the same triple gives the same
node, a new triple the next number, and a second pass asks for them all again and
gets no new node. Skipping the equality check on the node makes it fail.

AI-assisted: Claude Sonnet 5.5

Co-authored-by: Cursor <cursoragent@cursor.com>
@OreoFR

OreoFR commented Nov 30, 2026

Copy link
Copy Markdown
Collaborator

Checked by OreoFR on macOS 27.2.1, Apple M5, Rust (rustup), main a596adfac merged with head a0066d462.

  • MEASURED, cargo test --release -p leonida-shader: main 239 passed, 0 failed, 2 ignored; main + this PR 240 passed, 0 failed, 2 ignored. The extra one is the new the_unique_table_gives_a_triple_its_node_again_through_every_growth.
  • Not shown: a red run (the new test exercises the new open-addressing table, so it cannot run against main's code).
  • Not covered: the crate's Windows-only test modules, the DXIL identity over the archive and the -3 % wall time (they need the game's shaders).

AI-assisted: Claude Code

@KelboLive KelboLive left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The table's invariants are exactly right. The key is the full triple (nodes[node] == triple, structure.rs:172), the 11-bit tag only filters probes, growth recomputes the hash and tag from the nodes (:185-195) so no stale entry can survive a resize, there is no deletion (no tombstones), and the <= 1/2 load with one grow per insert guarantees an empty slot, so find's probe terminates. assert!(MAX_NODES == 1 << 21) ties the slot layout to the node range.

Differential against origin/main's HashMap canonicaliser: 400,000 triples (354,189 fresh, 43,269 repeats, 10 growths from 1,024 to 1,048,576 slots) produced identical ids and an identical nodes vector; re-asking all 354,189 triples after the growth made no new node; and a forced same-slot + same-tag pair (v = 64 / v = 1590) stayed distinct and survived another resize.

The committed test has teeth for every truncation I tried: comparing only the variable fails at once (a false hit returned 11893 where 28021 was due), returning on the tag alone returns the wrong node, and a growth that re-inserts under a different hash loses an existing triple and re-makes it. So "a tag collision cannot return a wrong node" is pinned rather than asserted.

One test suggestion: the random sequence only hits a tag-plus-slot collision by chance. Searching Unique::hash for a pair with equal (hash & mask, hash >> 53) (a few thousand hashes) and forcing it makes that path deterministic, as I did above.

No bug found; the only cost is the fixed 4 KB START table per Bools, which is negligible.

(Build note: the shared CARGO_TARGET_DIR was held by another leonida-shader test binary — two agents, one of them mine — so this was built in a separate target dir; not a problem with the PR.)

@MoonEyes

MoonEyes commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

Verified by MoonEyes (another person than the author) on head a0066d462 merged with main cd0c52fcf: I read the whole diff. cargo test -p leonida-shader: 411 passed, 0 failed (main 410).

In-game run with the six others of a batch on main 21e6bbf4b: RTX 4060 8 GB, NVIDIA 610.88, Windows 11 26300, -SeriesS -FrameGen 2, about 860 s in the world, then a second one of about 440 s, 0 device lost, 0 panic; pictures of the same scene compared with main, same. Black surfaces in early cutscenes while the PC's memory is full are there on plain main too.

AI-assisted (Claude Code).

@merzleckeier

Copy link
Copy Markdown
Contributor

I tested the full production-sized unique table in the actual Bools::mk on a0066d4 + 0ff8a53, native Linux and Rust 1.98.1. A local fixture inserted distinct triples up to the exact 2,097,152-node limit, then looked up every real node in a permuted order. All node IDs matched main, with the same checksum 083735d185e46f6c. An attempt to insert one more distinct node set overflow, while the last existing node still resolved to ID 2,097,151. The focused structure suite also passed (20 tests including the local fixture).

Five alternating solo invocations per arm gave median peak child RSS of about 128.1 MiB on main and 44.2 MiB with the PR. Median insertion was 55 ms versus 37 ms, and permuted lookup 21 ms versus 22 ms. Those are process-level measurements for this synthetic shape, separate from the end-to-end shader corpus figures. MEASURED with synthetic BDD inputs. AI-assisted (Codex).

@imShangLi

Copy link
Copy Markdown
Contributor

VERIFY-2788 — Linux, Fedora 45, Rust 1.98.1 (the pinned toolchain), no GPU device, no game files

Verdict: PASS. The new table gives the same answers as the HashMap it replaces — I ran the pull request's own model test against the old implementation and it passes there too — and it catches four of the five ways I broke it. The one it does not catch is a load-factor rule, which is a performance property rather than a correctness one.

Head a0066d46, base the current main 85ec1d33, merge base d8ca1824, 1 commit, 1 file, +153/−7: d3d12/crates/leonida-shader/src/structure.rs.

1. What it changes

Bools — the BDD behind the lane-mask structuriser — keeps the map from a (variable, low, high) triple to the node that holds it in a HashMap<(u32, Bool, Bool), Bool> with the Fx hasher. The pull request replaces it with an open-addressing table over node numbers:

/// A slot is four bytes: the node number in its low 21 bits and 11 bits of its triple's hash
/// above them, so that a probe past a slot of another triple does not read that node; 0 is an
/// empty slot (node 0 is a constant, in no triple). Never more than half full.
struct Unique {
    slots: Vec<u32>,
    mask: usize,          // one less than the number of slots, a power of two
}

The lookup is open addressing with linear probing; the tag is only a filter and the full triple comparison against the node's own entry is the truth:

if slot >> SLOT_NODE_BITS == tag {
    let node = slot & SLOT_NODE_MASK;
    if nodes[node as usize] == triple {
        return Ok(Bool(node));
    }
}

The table doubles when it is half full (self.nodes.len() * 2 > self.unique.slots.len()), and grow re-inserts every node but the two constants.

2. The repository's own red/green verifier: "red does not build"

$ python3 -I scripts/red_green.py pr2788 --no-fetch --base origin/main --crate leonida-shader --json
verdict: red does not build
red:  {"no_build": ["error[E0609]: no field `slots` on type `HashMap<(u32, Bool, Bool), Bool, BuildHasherDefault<Fx>>"]}
green: 249 tests, 0 failed (2 ignored)

The new test reads one field of the new structure:

assert!(b.unique.slots.len() >= 1 << 18, "{}", b.unique.slots.len());

so the red side (the base with only the pull request's tests) cannot compile — there is no slots on a HashMap. The green side is green: 249 tests, none failed.

That is a limitation of the test, not of the change: a test that cannot exist without the change cannot show that the change makes it pass. So I made the equivalent check myself.

3. The equivalence check I did instead: the same test on the old implementation

I took the pull request's test, dropped the one line that reads the new internals, and ran it against the old HashMap implementation on origin/main:

test structure::tests::the_unique_table_gives_a_triple_its_node_again_through_every_growth ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 248 filtered out

The test makes 400,000 random triples and checks each against a HashMap model: the same triple is the same node, a new triple is the next node, the node found really holds that triple, and after the table has doubled many times every triple is still found. It passes on both implementations.

That is the decisive result for a data-structure swap: the ground truth is the old implementation, not the game's data — and the two agree on the node number of every one of the 400,000 triples, including after the table has grown. The pull request's "DXIL identical" claim rides on exactly this: the node numbers are the same, so the diagram the structuriser builds is the same.

4. What the test does and does not discriminate

I broke the table five ways and ran the test each time:

mutation result
find trusts the tag and skips the comparison of the node's own entry FAILED — "a new triple is the next node" (left 580, right 1646)
grow skips one node (skip(2) → skip(3)) FAILED — the triple came back as a different node
the probe step is 3 instead of 1 (slots are stepped over) FAILED — a triple was not found
put does not write the tag FAILED — a triple came back as a different node
the growth rule is relaxed from half full to three quarters full passed — not caught

The last one is the only gap, and it is a performance invariant, not a correctness one: the table's cost is its probe length, and the test only pins the size from below (slots.len() >= 1 << 18), which a three-quarters-full table also satisfies. The "never more than half full" rule is in the code and in the pull request's own comment; nothing checks it.

The other four are the ones that matter, and the model catches each of them.

5. What I did not check

  • The performance claim — "−3 % wall" and the "11 % of the CPU time of the 500 slowest programs" (insert_no_grow 8.8 % plus reserve_rehash 2.3 %). That is a measurement on the game's own shaders; I have no game files and no corpus, so I can neither reproduce nor refute it. What I checked is the mechanism: 4 bytes a slot instead of a hash table's, and the same answers.
  • The 4-byte slot claim — read from the code (slots: Vec<u32>), not measured.
  • The end-to-end translation — the crate's 249 tests are green, but "the emitted DXIL is identical" over the corpus needs the corpus. The node-number equivalence in §3 is the closest thing I could check without it.
  • Windows and the driver's own allocator. Everything above is Linux with no GPU device.

AI-assisted: MiniMax M3.1 Flash.

@OreoFR

OreoFR commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

Merging (added to the merge queue). Head a0066d4 merges cleanly with main c4ca576. Claim: D3D12-SHADER-BDD-UNIQUE-COMPACT (coordination issue #2570). Red/green: merzleckeier (full-size table, same node IDs and checksum as main), imShangLi (Linux, PASS, catches four of five mutations). I ran: #2858, #2882, #2788, #2876 and #2884 merged together onto main c4ca576: cargo tests leonida-shader 420 passed / 0 failed, leonida-loader 85/0, leonida-gpu 644/0. In-game run: RTX 4070 Laptop 8 GB, NVIDIA 621.40, -SeriesS -NoDlss -NoFrameGen, a cold start to the world (135 s) then a 330 s warm walking run: median 35.4 ms (28.2 fps), private memory max 24.4 GB, 0 device lost. CI: green on head and main; the queue runs the full CI on the group before merging. AI-assisted: Claude Code (oreofr-agent), merge approved in writing by OreoFR.

@OreoFR
OreoFR added this pull request to the merge queue Dec 1, 2026
Merged via the queue into ProjectLeonida:main with commit f4c312a Dec 1, 2026
5 checks passed
@fiestorra

Copy link
Copy Markdown
Contributor

Confirmed on the title's own archive, and isolated to this change.

Method: leonida.exe translate "<title>\shaders.rpf" --jobs 16, release build, the whole archive (26,503 containers, 26,084 programs), two runs per build, in one sitting on a Ryzen 7 7800X3D / RTX 4090.

1fff69129                          (main, before the batch)   48.1 s   47.4 s
b511bfec3                          (just before this merge)   46.9 s   46.9 s
913b88b90                          (main, with this merge)    45.1 s   44.6 s

The twenty other commits in that batch are worth about a second (48.1/47.4 -> 46.9/46.9); this one is about two (46.9 -> 44.85), 4.3%, and it is the only commit between those two builds that touches the translator. The spread inside a build is 0.7 s at most, so the difference is outside it.

Two things it does not say:

  • the wall clock on this machine drifts with load: the same command took 30 s in an earlier session on the same archive. The numbers above are only comparable inside this sitting, which is why all six runs are here.
  • it is the translator only - translate writes nothing and makes no host pipelines. The precompile a start does is shaders into the cache plus the driver's pipeline creation, and this does not measure those.

What it means for a start: a smaller share of the one CPU-bound phase (the shader cache build measured 1.2 min with 16 workers on this machine), not a frame time.

AI-assisted: yes - DeepSeek v4.1 (flash).

Written with an AI assistant.

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.

7 participants