Shaders: retain pipeline-library file buffers without copying #3158

Open
storrmzz wants to merge 1 commit from upstream-pr/3158 into main
storrmzz commented 2026-11-28 13:59:19 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by storrmzz on 2026-11-28T13:59:19Z.


Loading a native pipeline library currently reads a Vec<u8> and copies the entire payload into Arc<[u8]>. Retain the original allocation in Arc<Vec<u8>> instead, reducing temporary CPU memory and copy work during preparation and warm startup. The library still owns the bytes for its full COM lifetime.

What is in it

  • Share the original serialized buffer through pipeline_library and warm_library; keep the file format and driver validation unchanged.
  • Add a GPU regression test for allocation identity and loading after the other owners are dropped; document the reduced allocation in README.
  • This is separate from #3100's previous-library imports and #2767's translated-DXIL sharing.

Tested

Rebase validation (2026-11-29)

  • Current head 00b4e95ec249fa4fc3253a28cd72bbf9dbcda316, rebased onto main d8bd9a38204667f3ca7dd9eeffcc2f1c937b07b0. Same Windows PC/toolchain as below.
  • Resolved the README conflict while retaining newer main documentation. The runtime/test changes from the original PR are preserved.
  • cargo build --workspace --jobs 2: passed.
  • cargo test -p xcl --lib shaders::pipeline_library::tests --jobs 2 -- --test-threads=1 --nocapture: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 2502 filtered out; finished in 4.54s Explicit SKIPPED: 0.
  • cargo test -p xcl --lib shaders::warm_library::tests --jobs 2 -- --test-threads=1 --nocapture: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 2505 filtered out; finished in 0.29s Explicit SKIPPED: 0.
  • git diff --check: passed. Full workspace suite, performance measurements and paired retail smoke were not rerun on this rebased head; earlier results below apply only to their named revisions.

Earlier revision results (historical; not the rebased head)

  • AMD Radeon 780M (32.0.31033.3), Ryzen 7 8840HS, 16 GB RAM, Windows 11 Pro 26300; Rust 1.100.0 MSVC, DXC/DXIL 1.9.2602.17.
  • PR source tree at 43b32ac33dbbbafed74be95f244aef54b3eaaf2a: cargo build --workspace --jobs 2 passed. cargo test --workspace --no-fail-fast --jobs 2 -- --test-threads=4 --nocapture: 2,132 passed, 9 failed, 48 ignored. Unchanged main e13d6250432d486502971781e9589a330e548d24, same commands: 2,131 passed, 9 failed, 48 ignored; the same nine tests failed. This is not a clean full-suite result.
  • cargo bench -p xcl --bench '*' --jobs 2 -- --test: all four optimized benchmark targets completed their smoke cases successfully (not a timing comparison).
  • Focused prototype run: cargo test -p xcl --lib shaders:: --jobs 2 -- --test-threads=1 --nocapture: 54 passed, 0 failed, 0 ignored, including two early-return skips (missing sample RPF / Developer Mode). The new allocation/lifetime test passed on the GPU; against the original implementation it failed at retain the original allocation (0 passed, 1 failed).
  • Both full suites printed 11 explicit SKIPPED cases: four per-lane f16 and two f32 conversion variants, driver-cache-control measurement (Developer Mode), two debug-layer title runs, heap-window OOM fallback (opt-in off), and texture-upload state validation (no debug layer). XCL_SAMPLE_* inputs are unset; sample-dependent early returns are not coverage.
  • Synthetic warm-file std::fs::read plus shared-buffer construction, two runs of nine alternating pairs per size (rustc -O, median):
File size Before → after, run 1 Before → after, run 2 Incremental Rust-heap peak
4 MiB 1.209 → 0.676 ms 1.428 → 0.824 ms about 8 → 4 MiB
64 MiB 21.888 → 13.292 ms 21.477 → 13.182 ms about 128 → 64 MiB
256 MiB 89.851 → 59.014 ms 87.861 → 58.668 ms about 512 → 256 MiB

This measures synthetic file loading and ownership transfer, not driver compilation, game loading, FPS, process commit or VRAM. Byte equality was checked outside the timer.

Failures reproduced on unchanged main
  • gpu::dxil::fuzz_tests::fuzz_validate_and_gpu_1
  • gpu::dxil::module::split::tests::dispatch_chain_oversized_loop_matches_whole
  • gpu::dxil::module::split::tests::dispatch_chain_wave32_live_loops
  • gpu::dxil::module::split::tests::dispatch_chain_wave64_live_loops_and_exchange
  • gpu::dxil::msaa_tests::direct_msaa_loads_precede_get_dimensions
  • gpu::recomp::heap_window_tests::gpu_heap_flat_reads_match_guarded_and_root_output
  • gpu::recomp::tests::gpu_compute_mode_dispatch_abi
  • test_title_runs_and_game_folder_is_untouched
  • two_pass_driver_cache_reuses_both_passes_and_recovers_corrupt_blobs

The test-title failure reports a post-Wait32/64 write mismatch; the two-pass cache test reports retained two-pass state. The shader failures are also present without this change.

Standalone benchmark reproduction

Save as library-buffer-probe.rs, compile with rustc -O --edition=2021 library-buffer-probe.rs, then run twice. Peak values count incremental live Rust allocator requests, excluding the existing comparison fixture. The buffers are synthetic, not serialized driver libraries; driver parsing is covered by the GPU tests rather than this benchmark.

use std::{alloc::{GlobalAlloc, Layout, System}, sync::{Arc, atomic::{AtomicUsize, Ordering}}, time::Instant, hint::black_box};
struct Meter;
static LIVE: AtomicUsize = AtomicUsize::new(0);
static PEAK: AtomicUsize = AtomicUsize::new(0);
fn added(n: usize) { let now = LIVE.fetch_add(n, Ordering::Relaxed) + n; PEAK.fetch_max(now, Ordering::Relaxed); }
unsafe impl GlobalAlloc for Meter {
    unsafe fn alloc(&self, l: Layout) -> *mut u8 { let p = unsafe { System.alloc(l) }; if !p.is_null() { added(l.size()); } p }
    unsafe fn dealloc(&self, p: *mut u8, l: Layout) { LIVE.fetch_sub(l.size(), Ordering::Relaxed); unsafe { System.dealloc(p,l) }; }
    unsafe fn realloc(&self, p: *mut u8, l: Layout, n: usize) -> *mut u8 { let q = unsafe { System.realloc(p,l,n) }; if !q.is_null() { LIVE.fetch_sub(l.size(),Ordering::Relaxed); added(n); } q }
}
#[global_allocator] static ALLOC: Meter = Meter;
fn run(path: &std::path::Path, new: bool, expected: &[u8]) -> (u128, usize) {
    let base = LIVE.load(Ordering::Relaxed); PEAK.store(base, Ordering::Relaxed);
    let t = Instant::now();
    let input = std::fs::read(path).unwrap();
    let ptr = input.as_ptr();
    if new {
        let shared = Arc::new(input);
        let elapsed = t.elapsed().as_nanos();
        let peak = PEAK.load(Ordering::Relaxed)-base;
        assert_eq!(shared.as_ptr(),ptr);
        assert_eq!(shared.as_slice(),expected);
        let copy = shared.clone(); drop(shared); assert_eq!(copy.as_slice(),expected);
        black_box(&copy);
        (elapsed,peak)
    } else {
        let shared: Arc<[u8]> = input.into();
        let elapsed = t.elapsed().as_nanos();
        let peak = PEAK.load(Ordering::Relaxed)-base;
        assert_eq!(&*shared,expected);
        black_box(&shared);
        (elapsed,peak)
    }
}
fn main() {
    let dir = std::env::temp_dir().join(format!("xcl-library-probe-{}",std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    println!("mib,round,before_ns,after_ns,before_peak_bytes,after_peak_bytes");
    for mib in [4,64,256] {
        let data: Vec<u8> = (0..mib*1024*1024).map(|i| (i as u8).wrapping_mul(37)).collect();
        let path=dir.join("synthetic.bin"); std::fs::write(&path,&data).unwrap();
        run(&path,false,&data); run(&path,true,&data);
        for round in 0..9 {
            let (a,b) = if round%2==0 { (run(&path,false,&data),run(&path,true,&data)) } else { let b=run(&path,true,&data); (run(&path,false,&data),b) };
            println!("{mib},{round},{},{},{},{}",a.0,b.0,a.1,b.1);
        }
    }
    std::fs::remove_dir_all(dir).unwrap();
}

Regression run
Not run: no retail title is available on this machine. Draft pending paired scripts/smoke.ps1 runs on main and this exact PR head.

Not tested

  • Retail startup/loading performance, real large pipeline-library files, NVIDIA/Intel, Wine, or a clean full suite. No claim of a game/FPS improvement.
  • The explicit GPU skips and sample-dependent early returns above.

AI use
This PR was created with AI assistance from OpenAI Codex (GPT-6).

<!-- greyfinch-sync:ivall/xcl:issue:5540879063 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3158). Originally posted by [storrmzz](https://github.com/storrmzz) on 2026-11-28T13:59:19Z. --- Loading a native pipeline library currently reads a `Vec<u8>` and copies the entire payload into `Arc<[u8]>`. Retain the original allocation in `Arc<Vec<u8>>` instead, reducing temporary CPU memory and copy work during preparation and warm startup. The library still owns the bytes for its full COM lifetime. **What is in it** - Share the original serialized buffer through `pipeline_library` and `warm_library`; keep the file format and driver validation unchanged. - Add a GPU regression test for allocation identity and loading after the other owners are dropped; document the reduced allocation in README. - This is separate from #3100's previous-library imports and #2767's translated-DXIL sharing. **Tested** **Rebase validation (2026-11-29)** - Current head `00b4e95ec249fa4fc3253a28cd72bbf9dbcda316`, rebased onto main `d8bd9a38204667f3ca7dd9eeffcc2f1c937b07b0`. Same Windows PC/toolchain as below. - Resolved the README conflict while retaining newer main documentation. The runtime/test changes from the original PR are preserved. - `cargo build --workspace --jobs 2`: passed. - `cargo test -p xcl --lib shaders::pipeline_library::tests --jobs 2 -- --test-threads=1 --nocapture`: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 2502 filtered out; finished in 4.54s Explicit SKIPPED: 0. - `cargo test -p xcl --lib shaders::warm_library::tests --jobs 2 -- --test-threads=1 --nocapture`: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 2505 filtered out; finished in 0.29s Explicit SKIPPED: 0. - `git diff --check`: passed. Full workspace suite, performance measurements and paired retail smoke were not rerun on this rebased head; earlier results below apply only to their named revisions. **Earlier revision results (historical; not the rebased head)** - AMD Radeon 780M (32.0.31033.3), Ryzen 7 8840HS, 16 GB RAM, Windows 11 Pro 26300; Rust 1.100.0 MSVC, DXC/DXIL 1.9.2602.17. - PR source tree at `43b32ac33dbbbafed74be95f244aef54b3eaaf2a`: `cargo build --workspace --jobs 2` passed. `cargo test --workspace --no-fail-fast --jobs 2 -- --test-threads=4 --nocapture`: **2,132 passed, 9 failed, 48 ignored**. Unchanged main `e13d6250432d486502971781e9589a330e548d24`, same commands: **2,131 passed, 9 failed, 48 ignored**; the same nine tests failed. This is not a clean full-suite result. - `cargo bench -p xcl --bench '*' --jobs 2 -- --test`: all four optimized benchmark targets completed their smoke cases successfully (not a timing comparison). - Focused prototype run: `cargo test -p xcl --lib shaders:: --jobs 2 -- --test-threads=1 --nocapture`: 54 passed, 0 failed, 0 ignored, including two early-return skips (missing sample RPF / Developer Mode). The new allocation/lifetime test passed on the GPU; against the original implementation it failed at `retain the original allocation` (0 passed, 1 failed). - Both full suites printed 11 explicit SKIPPED cases: four per-lane f16 and two f32 conversion variants, driver-cache-control measurement (Developer Mode), two debug-layer title runs, heap-window OOM fallback (opt-in off), and texture-upload state validation (no debug layer). `XCL_SAMPLE_*` inputs are unset; sample-dependent early returns are not coverage. - Synthetic warm-file `std::fs::read` plus shared-buffer construction, two runs of nine alternating pairs per size (`rustc -O`, median): | File size | Before → after, run 1 | Before → after, run 2 | Incremental Rust-heap peak | | --- | --- | --- | --- | | 4 MiB | 1.209 → 0.676 ms | 1.428 → 0.824 ms | about 8 → 4 MiB | | 64 MiB | 21.888 → 13.292 ms | 21.477 → 13.182 ms | about 128 → 64 MiB | | 256 MiB | 89.851 → 59.014 ms | 87.861 → 58.668 ms | about 512 → 256 MiB | This measures synthetic file loading and ownership transfer, not driver compilation, game loading, FPS, process commit or VRAM. Byte equality was checked outside the timer. <details> <summary>Failures reproduced on unchanged main</summary> - `gpu::dxil::fuzz_tests::fuzz_validate_and_gpu_1` - `gpu::dxil::module::split::tests::dispatch_chain_oversized_loop_matches_whole` - `gpu::dxil::module::split::tests::dispatch_chain_wave32_live_loops` - `gpu::dxil::module::split::tests::dispatch_chain_wave64_live_loops_and_exchange` - `gpu::dxil::msaa_tests::direct_msaa_loads_precede_get_dimensions` - `gpu::recomp::heap_window_tests::gpu_heap_flat_reads_match_guarded_and_root_output` - `gpu::recomp::tests::gpu_compute_mode_dispatch_abi` - `test_title_runs_and_game_folder_is_untouched` - `two_pass_driver_cache_reuses_both_passes_and_recovers_corrupt_blobs` The test-title failure reports a post-Wait32/64 write mismatch; the two-pass cache test reports retained two-pass state. The shader failures are also present without this change. </details> <details> <summary>Standalone benchmark reproduction</summary> Save as `library-buffer-probe.rs`, compile with `rustc -O --edition=2021 library-buffer-probe.rs`, then run twice. Peak values count incremental live Rust allocator requests, excluding the existing comparison fixture. The buffers are synthetic, not serialized driver libraries; driver parsing is covered by the GPU tests rather than this benchmark. ```rust use std::{alloc::{GlobalAlloc, Layout, System}, sync::{Arc, atomic::{AtomicUsize, Ordering}}, time::Instant, hint::black_box}; struct Meter; static LIVE: AtomicUsize = AtomicUsize::new(0); static PEAK: AtomicUsize = AtomicUsize::new(0); fn added(n: usize) { let now = LIVE.fetch_add(n, Ordering::Relaxed) + n; PEAK.fetch_max(now, Ordering::Relaxed); } unsafe impl GlobalAlloc for Meter { unsafe fn alloc(&self, l: Layout) -> *mut u8 { let p = unsafe { System.alloc(l) }; if !p.is_null() { added(l.size()); } p } unsafe fn dealloc(&self, p: *mut u8, l: Layout) { LIVE.fetch_sub(l.size(), Ordering::Relaxed); unsafe { System.dealloc(p,l) }; } unsafe fn realloc(&self, p: *mut u8, l: Layout, n: usize) -> *mut u8 { let q = unsafe { System.realloc(p,l,n) }; if !q.is_null() { LIVE.fetch_sub(l.size(),Ordering::Relaxed); added(n); } q } } #[global_allocator] static ALLOC: Meter = Meter; fn run(path: &std::path::Path, new: bool, expected: &[u8]) -> (u128, usize) { let base = LIVE.load(Ordering::Relaxed); PEAK.store(base, Ordering::Relaxed); let t = Instant::now(); let input = std::fs::read(path).unwrap(); let ptr = input.as_ptr(); if new { let shared = Arc::new(input); let elapsed = t.elapsed().as_nanos(); let peak = PEAK.load(Ordering::Relaxed)-base; assert_eq!(shared.as_ptr(),ptr); assert_eq!(shared.as_slice(),expected); let copy = shared.clone(); drop(shared); assert_eq!(copy.as_slice(),expected); black_box(&copy); (elapsed,peak) } else { let shared: Arc<[u8]> = input.into(); let elapsed = t.elapsed().as_nanos(); let peak = PEAK.load(Ordering::Relaxed)-base; assert_eq!(&*shared,expected); black_box(&shared); (elapsed,peak) } } fn main() { let dir = std::env::temp_dir().join(format!("xcl-library-probe-{}",std::process::id())); std::fs::create_dir_all(&dir).unwrap(); println!("mib,round,before_ns,after_ns,before_peak_bytes,after_peak_bytes"); for mib in [4,64,256] { let data: Vec<u8> = (0..mib*1024*1024).map(|i| (i as u8).wrapping_mul(37)).collect(); let path=dir.join("synthetic.bin"); std::fs::write(&path,&data).unwrap(); run(&path,false,&data); run(&path,true,&data); for round in 0..9 { let (a,b) = if round%2==0 { (run(&path,false,&data),run(&path,true,&data)) } else { let b=run(&path,true,&data); (run(&path,false,&data),b) }; println!("{mib},{round},{},{},{},{}",a.0,b.0,a.1,b.1); } } std::fs::remove_dir_all(dir).unwrap(); } ``` </details> **Regression run** Not run: no retail title is available on this machine. Draft pending paired `scripts/smoke.ps1` runs on main and this exact PR head. **Not tested** - Retail startup/loading performance, real large pipeline-library files, NVIDIA/Intel, Wine, or a clean full suite. No claim of a game/FPS improvement. - The explicit GPU skips and sample-dependent early returns above. **AI use** This PR was created with AI assistance from OpenAI Codex (GPT-6).
Foniass commented 2026-12-01 09:38:42 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-01T09:38:42Z.


Triage (#1607) – head 00b4e95

No open or merged PR makes this change, and main still stores the library as Arc<[u8]> (pipeline_library.rs NativeLibrary::_serialized / open_shared, warm_library.rs Ready). Vec<u8> into Arc<[u8]> does copy the whole buffer, so keeping Arc<Vec<u8>> does save that copy.
No problems found in the diff. The branch conflicts with main, where warm_library.rs has since been restructured (validate no longer takes the device), so it needs a rebase. The README sentence describes an internal allocation detail, not something users can act on.
Recommendation: keep open.

AI review: Claude Code (Claude Opus 5.5), diffs read only, not built or run; not checked by a human.

<!-- greyfinch-sync:ivall/xcl:comment:7306998366 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3158#issuecomment-7306998366). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-01T09:38:42Z. --- **Triage (#1607)** – head 00b4e95 No open or merged PR makes this change, and main still stores the library as `Arc<[u8]>` (pipeline_library.rs `NativeLibrary::_serialized` / `open_shared`, warm_library.rs `Ready`). `Vec<u8>` into `Arc<[u8]>` does copy the whole buffer, so keeping `Arc<Vec<u8>>` does save that copy. No problems found in the diff. The branch conflicts with main, where warm_library.rs has since been restructured (`validate` no longer takes the device), so it needs a rebase. The README sentence describes an internal allocation detail, not something users can act on. Recommendation: keep open. AI review: Claude Code (Claude Opus 5.5), diffs read only, not built or run; not checked by a human.
Foniass commented 2026-12-01 10:02:10 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-01T10:02:10Z.


Review (head 00b4e95, diff read, not a merge-check; draft, conflicts with main, PR description red: no smoke blocks):

  • Main rewrote the code it changes, but still makes the copy. 7599439b ("validate prepared libraries on the runtime device") changed warm_library.rs: validate(path, expected) no longer takes a device or opens the library, Ready gained driver and migration, and activate() goes through Ready / open_shared. So the validate hunk (~69-75) no longer applies. Main still holds the bytes as Arc<[u8]> (pipeline_library.rs ~160-185, warm_library.rs ~60, ~194, ~253), so the copy this removes is still there after a rebase.
  • Unmeasured saving. Steady-state memory is the same (the Vec is freed after the copy); what's saved is one memcpy and a short peak of one library's size at load. A library size and load time before and after would show whether it matters.
  • Related, unverified, and not introduced here: AMD's CreatePipelineLibrary reads a dword past the blob (#2859). Dropping the Arc header moves where the data sits in its allocation, so which file lengths expose the overread changes.
  • The two red CI tests (geometry_tests::msg_gs_done_emits_in_dxil, lower_mem::stage_guard_tests::geometry_export_rejected) failed on main 3b6a91ed too.

Fine: library is declared before _serialized (~162-163), so it drops first. The buffer is never mutated: NativeLibrary holds a clone, so get_mut can't succeed. The new GPU test checks pointer identity and loads a pipeline after the other owners are gone.

AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.

<!-- greyfinch-sync:ivall/xcl:comment:7307570825 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3158#issuecomment-7307570825). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-01T10:02:10Z. --- Review (head 00b4e95, diff read, not a merge-check; draft, conflicts with main, `PR description` red: no smoke blocks): - **Main rewrote the code it changes, but still makes the copy.** 7599439b ("validate prepared libraries on the runtime device") changed `warm_library.rs`: `validate(path, expected)` no longer takes a device or opens the library, `Ready` gained `driver` and `migration`, and `activate()` goes through `Ready` / `open_shared`. So the `validate` hunk (~69-75) no longer applies. Main still holds the bytes as `Arc<[u8]>` (`pipeline_library.rs` ~160-185, `warm_library.rs` ~60, ~194, ~253), so the copy this removes is still there after a rebase. - **Unmeasured saving.** Steady-state memory is the same (the `Vec` is freed after the copy); what's saved is one memcpy and a short peak of one library's size at load. A library size and load time before and after would show whether it matters. - Related, unverified, and not introduced here: AMD's `CreatePipelineLibrary` reads a dword past the blob (#2859). Dropping the `Arc` header moves where the data sits in its allocation, so which file lengths expose the overread changes. - The two red CI tests (`geometry_tests::msg_gs_done_emits_in_dxil`, `lower_mem::stage_guard_tests::geometry_export_rejected`) failed on main 3b6a91ed too. Fine: `library` is declared before `_serialized` (~162-163), so it drops first. The buffer is never mutated: `NativeLibrary` holds a clone, so `get_mut` can't succeed. The new GPU test checks pointer identity and loads a pipeline after the other owners are gone. AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/3158:upstream-pr/3158'
git switch 'upstream-pr/3158'

Merge

Merge the changes and update on Forgejo.

Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.

git switch 'main'
git merge --no-ff 'upstream-pr/3158'
git switch 'upstream-pr/3158'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/3158'
git switch 'upstream-pr/3158'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/3158'
git switch 'main'
git merge --squash 'upstream-pr/3158'
git switch 'main'
git merge --ff-only 'upstream-pr/3158'
git switch 'main'
git merge 'upstream-pr/3158'
git push origin 'main'
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
xcl-dev/xcl!3158
No description provided.