Skip to content

Shaders: share owned bytecode across derived and pending pipelines - #3091

Open
Prime1997 wants to merge 2 commits into
xcl-dev:nvidia-devfrom
Prime1997:codex/gdkx-base-shader-ownership
Open

Prime1997 wants to merge 2 commits into
xcl-dev:nvidia-devfrom
Prime1997:codex/gdkx-base-shader-ownership

Conversation

@Prime1997

@Prime1997 Prime1997 commented Nov 28, 2026 •

Copy link
Copy Markdown
Collaborator

Derived pipelines and pending asynchronous pipeline recipes retain shared immutable copies of shader bytes. The title can reuse its input memory without corrupting derived pipelines, and large pending queues avoid retaining one copy of the same shader per recipe. The weak sharing index is bounded, compares full bytes on hash collisions, and releases the payload at the last strong owner.

This extends the existing #3091. The pending-recipe sharing behavior overlaps the proposal in #827 (credit: Cattn); this NVIDIA implementation reuses the bounded Weak<Vec<u8>> index already present here. No separate duplicate shader-sharing PR is opened.

What is in it

  • Retain owned Base shader bytes across creation, derivation and depth-bias fallback.
  • Share live payloads between Base and asynchronous compute, graphics and stream descriptions, preserving shader keys and stream validation.
  • Ownership/lifetime, collision, index-bound, concurrency and synthetic backlog fixtures, plus README behavior notes.

Tested

  • Before the requested pause in further validation, 11 exact CPU-only tests passed, 0 failed, 0 ignored and 0 explicit skips on Windows x64. This was the combined 5d0833553c68d2afa327c913cd9a22f17ec6f45e source plus patch SHA256 1ea04e88f32675f0c5a4a64eb368479567ae9c1c79d4e7ab7da44ddc3a7c6ac5, not an individual-head full suite.
  • Tests covered async recipe ownership, stable shader keys, unreadable streams, Base lifetimes, collision/bound checks and concurrent sharing. Command: cargo test --locked -p xcl --lib --target-dir <isolated target> -- --exact --test-threads=4 --nocapture followed by the 11 exact test names in those groups; the exact command and outputs are retained locally.
  • The 1,024-recipe fixture retained 2 unique shader payloads totaling 81,920 bytes; copying both payloads into each recipe would require 83,886,080 bytes. This measures unique payload storage only, excluding descriptors, index/Arc overhead, process commit and VRAM.

Regression run
Not run for refreshed head 299c93f113c59eec315933c09432130569288f88. Previous-head results remain historical. The user requested a release candidate and interactive log monitoring, explicitly waiving further local shader/memory validation. This is not a passing GPU or gameplay result.

Not tested

  • Refreshed individual-head build/full suite and paired current-main/title regression.
  • Actual game memory savings, frame-time impact, hardware GPU regressions and AMD.

AI use
Codex (GPT-6) implemented the ownership repair, adapted #827's sharing concept to the existing bounded index, reviewed source and ran the CPU-only checks described above.

Optional temporary contributor/testing coordination: https://discord.gg/gK3y7WRRY

@Prime1997
Prime1997 force-pushed the codex/gdkx-base-shader-ownership branch from dcb2004 to 64aa28f Compare November 28, 2026 03:38
@Prime1997
Prime1997 marked this pull request as ready for review November 28, 2026 03:40
@thehollowedone

Copy link
Copy Markdown
Contributor

Independent Windows/NVIDIA check of #3091 head 64aa28f0, based on nvidia-dev e48e74ca.

The nine named shader-ownership fixtures pass on the RTX 3080 Ti (driver 621.35), including the native derived-pipeline check: 9 passed, 0 failed, 0 ignored, no reported skips. I ran the base_shader and GPU fixtures with cargo test --offline --locked -j 4 -p xcl --lib <filter> -- --test-threads=1, and the remaining named fixtures individually from the resulting lib test binary. Windows 11 build 26300, Ryzen 7 9800X3D, rustc 1.99.1 MSVC, DXC 1.8.2502.11.

The current-head full workspace run, cargo test --offline --locked -j 4 --workspace --no-fail-fast -- --test-threads=4, finished 1,908 passed, 1 failed, 48 ignored across 40 targets, with 26 explicit SKIPPED notices. The sole failure was console_mesh_caches_hlsl_compute_pass_in_memory_and_on_disk (DXIL not compiled yet). I reran that exact test on the unchanged e48e74ca parent; it failed there too, 0/1/0, with the same error. I did not run a retail smoke pair.

One bounded performance issue remains in share_base_shader: once 65,536 distinct shader keys remain live, every new key scans the entire weak index under its mutex, is not admitted, and cannot share a second request for the same bytes. This is a source-level scaling concern, not a measured retail bottleneck. A small test-only regression failed on the unchanged head, 0/1/0, because two requests for the same overflow stage returned distinct allocations. Admitting the new weak entry with bounded FIFO/clock eviction would keep the index capped and preserve existing Arc owners without a full scan on each saturated miss. Please cover repeated overflow keys and concurrent insertion when changing the admission policy.

Failing test-only regression
@@
+    #[test]
+    fn saturated_base_shader_index_shares_repeated_new_stage() {
+        let index: BaseShaderIndex = Mutex::new(None);
+        let a = share_base_shader(&index, 1, &[1], 2);
+        let b = share_base_shader(&index, 2, &[2], 2);
+        let c = share_base_shader(&index, 3, &[3], 2);
+        let again = share_base_shader(&index, 3, &[3], 2);
+        assert_eq!(a.as_slice(), &[1]);
+        assert_eq!(b.as_slice(), &[2]);
+        assert!(Arc::ptr_eq(&c, &again), "an overflow stage should share a live payload");
+    }

AI use: Codex (GPT-6.2 Sol) ran the tests and checked the finding; Codex (GPT-6.2 Astra) independently traced the index path.

@andrewDoing

Copy link
Copy Markdown

I tested the proposed bounded FIFO approach independently against head 64aa28f0 in a standalone Rust harness using the upstream interning function and a local candidate.

With all 65,536 index entries live, 16 threads requested four new payloads. The stock implementation returned distinct allocations for equal requests; the candidate shared one allocation per new payload, kept the index at its cap, and preserved the bytes held by every original owner. The candidate passed the existing collision and concurrency controls and the saturated case in 20/20 fresh processes.

The bound is on index entries, not total live shader memory: after a key is evicted, a later request can create a second copy while an older owner still retains the first. This is a synthetic candidate test; retail memory and timing were not measured.

AI use: OpenAI Codex with GPT-6.2 Astra built and ran the checks; Codex reviewed and prepared this report.

@DarkPanda69

DarkPanda69 commented Nov 28, 2026 •

Copy link
Copy Markdown

Update for head 299c93f (rebased on nvidia-dev 54225f5, plus "share pending pipeline shader payloads"): same device_x::tests:: command against the new merge-base 54225f5, 18 → 25 passed, 0 failed, no SKIPPED on both cards, the same seven changes as before. The GPU test again logged S6 native adapter=AMD Radeon RX 9070 XT … / … NVIDIA GeForce RTX 3060 …. The commit's two new tests, a_thousand_pending_graphics_recipes_keep_two_unique_shader_payloads and async_recipes_share_shader_bytes_and_keep_them_until_the_last_owner, pass too, run once with XCL_ADAPTER=Radeon (cargo test -p xcl --lib -- async_recipes_share_shader_bytes a_thousand_pending_graphics_recipes, 2 passed).

AMD run (listed as untested), with an RTX 3060 in the same PC: the seven new tests pass on both, and nothing else in device_x changes.

Tested: at the PR head 64aa28f against its merge-base with nvidia-dev, e48e74c (the diff doesn't apply as a patch on today's nvidia-dev 01b94f5). Debug, Rust 1.100.0, Windows 11 Pro 26200, Ryzen 7 5800X, card picked with XCL_ADAPTER; RX 9070 XT (RDNA4) driver 32.0.32029.2010, RTX 3060 driver 32.0.16.1088.

  • cargo test -p xcl --lib -- hle::d3d12x::device_x::tests:: --test-threads=1 --nocapture: merge-base 18 passed, 0 failed; PR 25 passed, 0 failed, 0 ignored, no SKIPPED, on both cards.
  • The only changes are the seven new tests, all ok. gpu_derived_pipeline_survives_original_shader_reuse logged S6 native adapter=AMD Radeon RX 9070 XT (16253 MiB VRAM); validation=PSO creation; dispatches=0, and the same with NVIDIA GeForce RTX 3060.

Not tested: the whole suite, a title, Intel.

AI use: Claude Code (Claude Opus 5.5) ran the tests on this machine and wrote this report.

@andrewDoing

Copy link
Copy Markdown

I extended the existing pipeline-chain fixture with a native GPU draw on RTX 5070 / NVIDIA 616.92 at head 64aa28f0 (test-only overlay). After overwriting the original VS/PS bytecode, releasing the base, creating the grandchild, and releasing the child, I bound the grandchild for a scissored draw.

After a bounded completion fence, readback showed exactly eight expected red pixels in the left two columns and eight untouched blue-clear pixels in the right two. The device remained healthy and the focused test passed with no skips. The existing fallback counters were checked at base, child, and grandchild creation. The fixture intentionally kept the root signature alive.

This extends the creation-only coverage to one graphics draw after those shader-bytecode and ancestor lifetimes. It does not establish general resource lifetime, retail rendering, or memory savings.

AI use: OpenAI Codex with GPT-6.2 Astra built and ran the fixture; Codex reviewed and prepared this report.

Royalflamejlh added a commit to Royalflamejlh/xcl that referenced this pull request Nov 28, 2026
@thehollowedone

Copy link
Copy Markdown
Contributor

Follow-up to my saturated-index regression on head 64aa28f0. I implemented a local candidate that keeps a bounded FIFO of weak index keys. A new key evicts one indexed key at capacity instead of scanning all 65,536 entries; existing Arc owners keep their payloads. Same-key hash collisions retain their queue position and replace only the weak index entry. This complements andrewDoing's independent saturation check.

The previously posted repeated-overflow fixture failed on the unchanged head (0/1/0). With this candidate, cargo test --offline --locked -j 4 -p xcl --lib hle::d3d12x::device_x::tests -- --test-threads=1 passed 27/0/0, including the native RTX 3080 Ti fixture, existing collision/concurrency tests, repeated overflow and a new eight-thread saturated insertion. git diff --check passed. Windows 11 build 26300, RTX 3080 Ti / 621.35, Ryzen 7 9800X3D, rustc 1.99.1 MSVC. This candidate has not had a full workspace suite or paired smoke; the exact head's earlier full-suite result is in my linked report.

Apply-ready candidate diff
diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs
index be8051bb..ec952ada 100644
--- a/crates/xcl/src/hle/d3d12x/device_x.rs
+++ b/crates/xcl/src/hle/d3d12x/device_x.rs
@@ -344,29 +344,40 @@ fn rd64(d: &[u8], o: usize) -> u64 {
     u64::from_le_bytes(d[o..o + 8].try_into().unwrap())
 }
 
-type BaseShaderIndex = Mutex<Option<HashMap<(u64, usize), std::sync::Weak<Vec<u8>>>>>;
+#[derive(Default)]
+struct BaseShaderEntries {
+    blobs: HashMap<(u64, usize), std::sync::Weak<Vec<u8>>>,
+    order: std::collections::VecDeque<(u64, usize)>,
+}
+
+type BaseShaderIndex = Mutex<Option<BaseShaderEntries>>;
 
 /// A weak index shares live Base shader copies, without keeping their byte buffers alive.
 /// Unlike Arc<[u8]>, the Vec payload is released at the last strong reference, even while
 /// this index keeps a weak reference. The index itself is bounded too.
 fn share_base_shader(index: &BaseShaderIndex, hash: u64, bytes: &[u8], limit: usize) -> Arc<Vec<u8>> {
     let key = (hash, bytes.len());
-    let cached = index.lock().unwrap().as_ref().and_then(|m| m.get(&key)).and_then(std::sync::Weak::upgrade);
+    let cached = index.lock().unwrap().as_ref().and_then(|m| m.blobs.get(&key)).and_then(std::sync::Weak::upgrade);
     if let Some(cached) = cached.filter(|v| v.as_slice() == bytes) {
         return cached;
     }
     // Copy outside the lock; another creation may have published the same bytes meanwhile.
     let owned = Arc::new(bytes.to_vec());
     let mut g = index.lock().unwrap();
-    let m = g.get_or_insert_with(HashMap::new);
-    if let Some(cached) = m.get(&key).and_then(std::sync::Weak::upgrade).filter(|v| v.as_slice() == bytes) {
+    let m = g.get_or_insert_with(BaseShaderEntries::default);
+    if let Some(cached) = m.blobs.get(&key).and_then(std::sync::Weak::upgrade).filter(|v| v.as_slice() == bytes) {
         return cached;
     }
-    if m.len() >= limit {
-        m.retain(|_, v| v.strong_count() != 0);
-    }
-    if m.len() < limit || m.contains_key(&key) {
-        m.insert(key, Arc::downgrade(&owned));
+    if limit != 0 {
+        if !m.blobs.contains_key(&key) {
+            if m.blobs.len() >= limit {
+                if let Some(oldest) = m.order.pop_front() {
+                    m.blobs.remove(&oldest);
+                }
+            }
+            m.order.push_back(key);
+        }
+        m.blobs.insert(key, Arc::downgrade(&owned));
     }
     owned
 }
@@ -1706,19 +1717,52 @@ mod tests {
         let b = share_base_shader(&index, 7, &[5], 2);
         let uncached = share_base_shader(&index, 9, &[6], 2);
         assert_eq!(uncached.as_slice(), &[6], "full index still returns owned bytes");
-        assert_eq!(index.lock().unwrap().as_ref().unwrap().len(), 2);
+        assert_eq!(index.lock().unwrap().as_ref().unwrap().blobs.len(), 2);
         let weak = Arc::downgrade(&collision);
         drop(collision);
         assert!(weak.upgrade().is_none(), "the index does not keep the Vec or its payload live");
         let c = share_base_shader(&index, 9, &[6], 2);
         let keys = index.lock().unwrap();
         let keys = keys.as_ref().unwrap();
-        assert_eq!(keys.len(), 2);
-        assert!(!keys.contains_key(&(7, 3)), "dead entry pruned at capacity");
-        assert!(keys.contains_key(&(7, 1)) && keys.contains_key(&(9, 1)), "length is part of identity");
+        assert_eq!(keys.blobs.len(), 2);
+        assert!(!keys.blobs.contains_key(&(7, 3)), "oldest entry evicted at capacity");
+        assert!(keys.blobs.contains_key(&(7, 1)) && keys.blobs.contains_key(&(9, 1)), "length is part of identity");
         drop((a, same, b, c, uncached));
     }
 
+    #[test]
+    fn saturated_base_shader_index_shares_repeated_new_stage() {
+        let index: BaseShaderIndex = Mutex::new(None);
+        let a = share_base_shader(&index, 1, &[1], 2);
+        let b = share_base_shader(&index, 2, &[2], 2);
+        let c = share_base_shader(&index, 3, &[3], 2);
+        let again = share_base_shader(&index, 3, &[3], 2);
+        assert_eq!(a.as_slice(), &[1]);
+        assert_eq!(b.as_slice(), &[2]);
+        assert!(Arc::ptr_eq(&c, &again), "an overflow stage should share a live payload");
+        let entries = index.lock().unwrap();
+        let entries = entries.as_ref().unwrap();
+        assert_eq!((entries.blobs.len(), entries.order.len()), (2, 2));
+    }
+
+    #[test]
+    fn concurrent_overflow_shares_one_shader_copy() {
+        let index = Arc::new(Mutex::new(None));
+        let held = [share_base_shader(&index, 1, &[1], 2), share_base_shader(&index, 2, &[2], 2)];
+        let gate = Arc::new(std::sync::Barrier::new(8));
+        let threads: Vec<_> = (0..8).map(|_| {
+            let (index, gate) = (index.clone(), gate.clone());
+            std::thread::spawn(move || {
+                gate.wait();
+                share_base_shader(&index, 3, &[3; 1024], 2)
+            })
+        }).collect();
+        let copies: Vec<_> = threads.into_iter().map(|t| t.join().unwrap()).collect();
+        assert!(copies.iter().all(|v| Arc::ptr_eq(&copies[0], v)));
+        assert_eq!(index.lock().unwrap().as_ref().unwrap().blobs.len(), 2);
+        drop(held);
+    }
+
     #[test]
     fn concurrent_bases_publish_one_shader_copy() {
         let index = Arc::new(Mutex::new(None));
@@ -1732,7 +1776,7 @@ mod tests {
         }).collect();
         let copies: Vec<_> = threads.into_iter().map(|t| t.join().unwrap()).collect();
         assert!(copies.iter().all(|v| Arc::ptr_eq(&copies[0], v)));
-        assert_eq!(index.lock().unwrap().as_ref().unwrap().len(), 1);
+        assert_eq!(index.lock().unwrap().as_ref().unwrap().blobs.len(), 1);
     }
 
     #[test]

AI use: Codex (GPT-6.2 Sol) wrote the candidate, reviewed the bounded index and ownership path, and ran the stated tests.

Own shader bytes for each retained graphics base and share equal live bytecode through a bounded weak index. Native derivation survives original-buffer reuse and parent release. The 1024-pipeline fixture retains 81920 payload bytes instead of 83886080 with separate copies; this is payload accounting, not process RAM. Full-suite and retail merge checks remain pending.

Assisted-by: Codex (GPT-6)
Adapt the shader interning proposal in PR xcl-dev#827 using the bounded weak Vec ownership index from xcl-dev#3091. Pending compute, graphics and stream recipes share live immutable copies while preserving title-memory lifetime and cache keys. Source patch passed 11 focused CPU tests before integration; full GPU/gameplay validation is waived for this user test build.

Concept credit: Cattn / PR xcl-dev#827. Implementation and focused checks: Codex (GPT-6).
@Prime1997 Prime1997 changed the title Shaders: retain shared bytecode for derived pipelines Shaders: share owned bytecode across derived and pending pipelines Nov 28, 2026
@Prime1997
Prime1997 force-pushed the codex/gdkx-base-shader-ownership branch from 64aa28f to 299c93f Compare November 28, 2026 08:40
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