Skip to content

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

Draft
storrmzz wants to merge 1 commit into
xcl-dev:mainfrom
storrmzz:shaders/reuse-pipeline-library-buffer
Draft

storrmzz wants to merge 1 commit into
xcl-dev:mainfrom
storrmzz:shaders/reuse-pipeline-library-buffer

Conversation

@storrmzz

@storrmzz storrmzz commented Nov 28, 2026 •

Copy link
Copy Markdown

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

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

Converting a serialized library from Vec<u8> to Arc<[u8]> allocates and
copies its whole payload. Keep the original allocation in Arc<Vec<u8>>
through validation, publication and runtime ownership instead.

Test the allocation identity and load a pipeline after the other buffer
owners have been dropped. The test fails on the original implementation.
@storrmzz
storrmzz force-pushed the shaders/reuse-pipeline-library-buffer branch from 43b32ac to 00b4e95 Compare November 29, 2026 14:38
@github-actions github-actions Bot added area:docs-ci Documentation, scripts, workflows, repo governance area:shaders Shader cache, PSO compilation, pipeline libraries, precompilation gpu:both Code affects both AMD and NVIDIA GPUs (scope tag; see needs:*-test for remaining checks) needs-pr-check Failing the PR description check (CONTRIBUTING.md) labels Nov 29, 2026
@Foniass

Foniass commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

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

Foniass commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

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. 7599439 ("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 (D3D12.X: pipeline library blob has a readable dword after its end #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 3b6a91e 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:docs-ci Documentation, scripts, workflows, repo governance area:shaders Shader cache, PSO compilation, pipeline libraries, precompilation gpu:both Code affects both AMD and NVIDIA GPUs (scope tag; see needs:*-test for remaining checks) needs-pr-check Failing the PR description check (CONTRIBUTING.md)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants