From ec80c0716d81c57eb1d6d192e380fee9635a3a7e Mon Sep 17 00:00:00 2001 From: bmjask <11672696+bmjask@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:58:16 -0500 Subject: [PATCH 1/3] D3D12.X: reuse offline whole compute pipelines before splitting --- README.md | 3 + crates/xcl/src/hle/d3d12x/real.rs | 85 +++++++++++++++-- .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 2 +- crates/xcl/tests/gpu_compute_e2e.rs | 92 ++++++++++++++++++- 4 files changed, 171 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 786f6bfc3d..321cc03a9e 100644 --- a/README.md +++ b/README.md @@ -232,6 +232,9 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder
Switches, caches, logs and the files XCL writes +- For compute shaders that XCL can split, the runtime first tries the saved driver blob for + the whole shader. A usable blob lets the GPU run it in one dispatch. If the blob is missing + or the driver rejects it, XCL builds the split pieces. - **`--pipelines` size cap**: a compute program whose DXIL is over 8 MiB and that has no saved blob is left to the runtime instead of being compiled in the pass — those compiles take tens of minutes and gigabytes and stopped the pass on the biggest programs. `XCL_PIPELINE_MAX_KB` diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 91085d3933..76f31d4daf 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4342,7 +4342,12 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const return Some(Err(())); } let record = crate::gpu::shader::fnv64(cs); - if let Some(plan) = compiled.dispatch_chain { + let warm = compiled.dispatch_chain.as_ref().and_then(|_| { + let rs = abi_rs_for(this, &compiled.samplers)?; + let result = compute_container(this, f, d, rs, &dxil, record, riid, ppv, ComputeBuild::CachedWhole); + (result.0 >= 0).then_some((rs, result)) + }); + if let Some(plan) = compiled.dispatch_chain.filter(|_| warm.is_none()) { if let Some(rs) = dispatch_chain::build(this, f, d, riid, ppv, record, &dxil, &compiled.samplers, plan) { LAST_COMPUTE_RS.with(|c| c.set(rs)); note_pso_rs(*ppv, rs as *mut c_void); @@ -4355,9 +4360,14 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const return Some(Ok(0)); } } - let Some(rs) = abi_rs_for(this, &compiled.samplers) else { return Some(Err(())) }; + let (rs, (hr, in_driver, reused)) = match warm { + Some(hit) => hit, + None => { + let Some(rs) = abi_rs_for(this, &compiled.samplers) else { return Some(Err(())) }; + (rs, compute_container(this, f, d, rs, &dxil, record, riid, ppv, ComputeBuild::Whole)) + } + }; LAST_COMPUTE_RS.with(|c| c.set(rs as usize)); - let (hr, in_driver, reused) = compute_container(this, f, d, rs, &dxil, record, riid, ppv, false); if hr < 0 { // A huge program's verdict in the log itself: `note_translation_error` goes to the // report, or to the notes of a cached-only attempt – a retail title's 13.8 MB program @@ -4395,10 +4405,18 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const pub(super) mod dispatch_chain; pub(crate) use dispatch_chain::log_counts as log_dispatch_chain_counts; -/// `chained`: built with the dispatch chain's root signature (`dispatch_chain`), whose driver blobs -/// are kept apart on disk from the same DXIL's under the title's. +#[derive(Clone, Copy, PartialEq)] +enum ComputeBuild { + Whole, + // Try the existing whole program before building a chain. A miss or rejected blob falls + // through to building the pieces, whose cold build is cheaper. + CachedWhole, + // The chain root signature has a separate on-disk namespace. + Chain, +} + unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPELINE_STATE_DESC, rs: *mut c_void, - dxil: &[u8], record: u64, riid: *const GUID, ppv: *mut *mut c_void, chained: bool) -> (HRESULT, std::time::Duration, bool) { + dxil: &[u8], record: u64, riid: *const GUID, ppv: *mut *mut c_void, mode: ComputeBuild) -> (HRESULT, std::time::Duration, bool) { let mut copy: D3D12_COMPUTE_PIPELINE_STATE_DESC = std::ptr::read(d); copy.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs); copy.CS = bytecode(dxil); @@ -4408,13 +4426,15 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL let key = compute_blob_key(dxil, rs as usize, copy.Flags.0); let mut cached = compute_blob(key); // … and one built in an earlier run gets the blob kept on disk then (`driver_cache`) - let disk = driver_cache::path_for(dxil, copy.Flags.0, chained); + let disk = driver_cache::path_for(dxil, copy.Flags.0, mode == ComputeBuild::Chain); let from_disk = cached.is_none(); if from_disk { cached = disk.as_deref().and_then(driver_cache::load).map(std::sync::Arc::new); } if let Some(b) = &cached { copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: b.as_ptr() as *const c_void, CachedBlobSizeInBytes: b.len() }; + } else if mode == ComputeBuild::CachedWhole { + return (E_INVALIDARG, std::time::Duration::ZERO, false); } // in the background, a few at a time and within the commit headroom the program asks for let (mut hr, mut in_driver) = driver_compile_identified( @@ -4430,6 +4450,9 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL if from_disk { driver_cache::note(false, disk.as_deref()); } + if mode == ComputeBuild::CachedWhole { + return (hr, in_driver, false); + } copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); let (retried, took) = driver_compile_identified( "compute retry", @@ -4683,6 +4706,54 @@ fn forget_compute_blob(key: (u64, usize, i32)) { #[cfg(test)] mod compute_blob_tests { + #[test] + fn recorded_split_selects_cached_whole_or_pieces() { + use super::*; + use crate::gpu::recomp::pso::{console_to_dxil_for, Stage}; + let Some(input) = std::env::var_os("XCL_SAMPLE_RUNTIME_COMPUTE") else { return }; + let cache = std::path::PathBuf::from(std::env::var_os("XCL_DXIL_CACHE").expect("private empty replay cache")); + let mode = std::env::var("XCL_SAMPLE_CACHE_CASE").unwrap(); + assert_eq!(super::super::backend(), super::super::Backend::Real); + let raw = device_raw(); + let code = std::fs::read(input).unwrap(); + let c = console_to_dxil_for(&code, Stage::Compute, 0, wave32_only(raw)).unwrap(); + assert!(c.dispatch_chain.is_some()); + let path = driver_cache::path(&c.dxil, 0).unwrap(); + assert!(path.starts_with(&cache)); + assert_eq!(path.exists(), mode == "offline", "expected driver cache entry at {}", path.display()); + unsafe { + let root = abi_rs_for(raw, &c.samplers).unwrap(); + let create: PsoFn = std::mem::transmute(orig_fn(raw, slot_of(raw, "CreateComputePipelineState"))); + let iid = pc_iid(Kind::PipelineState); + match mode.as_str() { + "hit" => { + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), CS: bytecode(&c.dxil), ..Default::default() + }; + let mut ptr = std::ptr::null_mut(); + assert!(create(raw, (&desc as *const D3D12_COMPUTE_PIPELINE_STATE_DESC).cast(), &iid, &mut ptr) >= 0); + let blob = ID3D12PipelineState::from_raw(ptr).GetCachedBlob().unwrap(); + assert!(driver_cache::write(&path, std::slice::from_raw_parts(blob.GetBufferPointer().cast(), blob.GetBufferSize()))); + } + "stale" => assert!(driver_cache::write(&path, b"invalid driver blob")), + "miss" | "offline" => (), + _ => panic!("unknown replay case"), + } + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { CS: bytecode(&code), ..Default::default() }; + let mut out = std::ptr::null_mut(); + let start = std::time::Instant::now(); + let hr = translated_compute_pso_once(raw, create, (&desc as *const D3D12_COMPUTE_PIPELINE_STATE_DESC).cast(), &iid, &mut out) + .expect("recognized compute shader").expect("translated pipeline"); + assert!(hr >= 0 && !out.is_null()); + let whole = LAST_COMPUTE_RS.with(|s| s.get()) == root as usize; + println!("RUNTIME_CACHE case={mode} whole={whole} elapsed_ms={:.2}", start.elapsed().as_secs_f64()*1000.); + let expected_whole = matches!(mode.as_str(), "hit" | "offline"); + assert_eq!(whole, expected_whole); + assert_eq!(path.exists(), expected_whole); + drop(ID3D12PipelineState::from_raw(out)); + } + } + #[test] fn a_blob_is_found_only_for_the_same_program_root_signature_and_flags_and_is_forgotten() { let dxil = vec![7u8; 1000]; diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 958c9e9c28..6fa76b4cbf 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -43,7 +43,7 @@ impl PipelineBuilder { let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { NodeMask: self.node, Flags: self.flags, ..Default::default() }; let mut raw = std::ptr::null_mut(); let (hr, _, _) = compute_container(self.device.as_raw(), self.create, &desc, self.signature.as_raw(), - dxil, self.record, iid, &mut raw, true); + dxil, self.record, iid, &mut raw, ComputeBuild::Chain); (hr >= 0 && !raw.is_null()).then(|| ID3D12PipelineState::from_raw(raw)) } } diff --git a/crates/xcl/tests/gpu_compute_e2e.rs b/crates/xcl/tests/gpu_compute_e2e.rs index ce77d502e0..5ffa519a96 100644 --- a/crates/xcl/tests/gpu_compute_e2e.rs +++ b/crates/xcl/tests/gpu_compute_e2e.rs @@ -87,6 +87,86 @@ fn console_cs_flags(code: &[u8], rsrc2: u32, threads: [u32; 3], flags: u32) -> V const V: u64 = 256; // VALU source code of v0 +/// Make several guarded arithmetic blocks so the same shader has both whole and split forms. +fn guarded_adds() -> Vec { + let mut code = Vec::new(); + let mut op = |name, enc, fields: &[(&str, u64)]| code.extend(encode(name, enc, fields, None).unwrap()); + op("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 126)]); + op("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", V)]); + for add in 1..=5 { + op("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 1), ("SSRC1", 128 + add)]); + op("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 2)]); + op("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 128 + add), ("VSRC1", 2)]); + op("V_XOR_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 135), ("VSRC1", 2)]); + } + op("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 130), ("VSRC1", 0)]); + op("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 0), ("VSRC1", 4)]); + op("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 128)]); + op("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 4), ("DATA", 2), ("SADDR", 0x7d)]); + op("S_ENDPGM", "ENC_SOPP", &[]); + code +} + +#[test] +fn split_compute_prefers_the_offline_whole_pipeline() { + use std::{fs, process::Command}; + let blob = console_cs(&guarded_adds(), 2 << 1 | 1 << 7, [32,1,1]); + if let Ok(case) = std::env::var("XCL_TEST_WHOLE_CASE") { + assert_eq!(xcl::hle::d3d12x::backend(), xcl::hle::d3d12x::Backend::Real); + let raw = real::device_raw(); + let dev = unsafe { ID3D12Device::from_raw_borrowed(&raw) }.unwrap(); + let compiled = xcl::gpu::recomp::pso::console_to_dxil_for(&blob, xcl::gpu::recomp::pso::Stage::Compute, 0, true).unwrap(); + assert!(compiled.dispatch_chain.is_some()); + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: blob.as_ptr().cast(), BytecodeLength: blob.len(), + }, ..Default::default() }; + let pso: ID3D12PipelineState = unsafe { dev.CreateComputePipelineState(&desc) }.unwrap(); + let resolved = pso_async::resolve_wait(pso.as_raw() as usize); + assert!(real::is_translated_compute(resolved)); + let rs = real::pso_root_signature(resolved).unwrap() as *mut std::ffi::c_void; + assert_eq!(Some(rs) == real::abi_rs_cached(), case == "hit", "selected root signature"); + if case == "hit" { + let raw = resolved as *mut std::ffi::c_void; + let real = unsafe { ID3D12PipelineState::from_raw_borrowed(&raw) }.unwrap(); + let rs = unsafe { ID3D12RootSignature::from_raw_borrowed(&rs) }.unwrap(); + let mut expected = vec![0xdeadbeef; 64]; + let out = runner::dispatch_on(dev, real, rs, [1,1,1], &[32,3], &expected).unwrap(); + for lane in 0..32 { + expected[8+lane] = [1,2,4,5].into_iter().fold(lane as u32, |v, add| (v + add) ^ 7); + } + assert_eq!(out, expected); + } + return; + } + if xcl::gpu::recomp::dxc::location().is_err() || !runner::wave32_supported().unwrap_or(false) { + return runner::skip_test("requires DXC and a wave32 GPU"); + } + let dir = std::env::temp_dir().join(format!("xcl-guarded-adds-{}-{}", std::process::id(), + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos())); + let input = dir.join("input"); + let cache = dir.join("cache"); + fs::create_dir_all(&input).unwrap(); + fs::write(input.join("guarded.bin"), blob).unwrap(); + let run = |cmd: &mut Command| { + let out = cmd.env("XCL_DIRECT_DXIL","1") + .env("XCL_DXIL_CACHE",&cache).env("XCL_PSO_DISK_CACHE","1").output().unwrap(); + assert!(out.status.success(), "{}\n{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)); + }; + // Seed the ordinary whole PSO offline, then force the runtime to choose between it and a split chain. + run(Command::new(env!("CARGO_BIN_EXE_xcl")).arg("shaders").arg(&input).args(["--precompile","--pipelines"]) + .env("XCL_DIRECT_SPLIT_INSTRUCTIONS","12500")); + let mut files = fs::read_dir(cache.join("driver")).unwrap(); + let blob = files.next().unwrap().unwrap().path(); + assert!(files.next().is_none() && blob.metadata().unwrap().len() > 0); + for case in ["hit","stale","miss"] { + if case == "stale" { fs::write(&blob, b"rejected driver cache fixture").unwrap(); } + run(Command::new(std::env::current_exe().unwrap()).args(["--exact","split_compute_prefers_the_offline_whole_pipeline","--nocapture"]) + .env("XCL_DIRECT_SPLIT_INSTRUCTIONS","12").env("XCL_TEST_WHOLE_CASE",case)); + assert_eq!(blob.exists(), case == "hit"); + } + fs::remove_dir_all(dir).unwrap(); +} + #[test] fn offline_compute_pipeline_is_reused_by_a_second_process() { use std::{fs, process::Command}; @@ -108,6 +188,7 @@ fn offline_compute_pipeline_is_reused_by_a_second_process() { let run = |enabled: bool| { let out = Command::new(env!("CARGO_BIN_EXE_xcl")).arg("shaders").arg(&input) .args(["--precompile", "--pipelines"]).env("XCL_DXIL_CACHE", &cache) + .env("TMP", &dir).env("TEMP", &dir).env("XCL_DXIL_DUMP", "all") .env("XCL_PSO_DISK_CACHE", if enabled { "1" } else { "0" }).output().unwrap(); let text = String::from_utf8_lossy(&out.stdout).into_owned(); assert!(out.status.success() && text.contains("pipelines made on the GPU 1, refused 0"), "{text}\n{}", String::from_utf8_lossy(&out.stderr)); @@ -116,8 +197,10 @@ fn offline_compute_pipeline_is_reused_by_a_second_process() { run(false); assert!(!cache.join("driver").exists()); run(true); - let dxil_file = fs::read_dir(&cache).unwrap().flatten().map(|e| e.path()) - .find(|p| p.extension().is_some_and(|ext| ext == "dxil")).unwrap(); + let direct = dir.join("xcl-dxil-dump"); + let dxil_dir = if direct.is_dir() { &direct } else { &cache }; + let dxil_file = fs::read_dir(dxil_dir).unwrap().map(|e| e.unwrap().path()) + .find(|p| p.extension().is_some_and(|ext| ext == "dxil")).expect("compiled fixture DXIL"); let dxil = fs::read(dxil_file).unwrap(); let name = format!("{:016x}-{:x}-0.pso", xcl::gpu::shader::fnv64(&dxil), dxil.len()); let driver_file = cache.join("driver").join(name); @@ -125,7 +208,10 @@ fn offline_compute_pipeline_is_reused_by_a_second_process() { let warm = run(true); // A blob from an earlier driver can be refused. The normal build must still succeed. fs::write(&driver_file, b"invalid cached pipeline").unwrap(); - run(true); + let stale = run(true); + assert!(stale.contains("pipelines loaded from the driver cache 0"), "{stale}"); + let repaired = run(true); + assert!(repaired.contains("pipelines loaded from the driver cache 1"), "{repaired}"); let _ = fs::remove_dir_all(&dir); assert!(warm.contains("pipelines loaded from the driver cache 1"), "{warm}"); } From c836ecd9ff0a645e108722cc48890211ca8bb9f5 Mon Sep 17 00:00:00 2001 From: bmjask <11672696+bmjask@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:58:17 -0500 Subject: [PATCH 2/3] Recompiler: compact repeated split-wave compute blocks with atomics --- crates/xcl/src/gpu/dxil/compact.rs | 21 +++++++++++++++++---- crates/xcl/src/gpu/dxil/compact_tests.rs | 15 +++++++++++++-- crates/xcl/src/gpu/dxil/kernel.rs | 10 +++++++--- 3 files changed, 37 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/compact.rs b/crates/xcl/src/gpu/dxil/compact.rs index b5d615a297..b84298be5e 100644 --- a/crates/xcl/src/gpu/dxil/compact.rs +++ b/crates/xcl/src/gpu/dxil/compact.rs @@ -39,15 +39,28 @@ impl Plan { } } -/// Whether a program takes the form by itself: large, mostly repeated blocks, small tables. -pub fn wanted(cfg: &Cfg, p: &Plan, tables: usize) -> bool { +/// A consumed atomic result prevents cutting a dispatch into independent pipelines. +/// Consider a compact whole pipeline for branch-heavy split-wave compute shaders instead. +pub(super) fn atomic_candidate(cfg: &Cfg) -> bool { + cfg.rpo.len() >= 250 && cfg.rpo.iter().flat_map(|&b| &cfg.blocks[b].insts).any(|&i| { + let d = &cfg.insts[i]; + d.inst.name == "BUFFER_ATOMIC_ADD" && crate::gpu::rdna2::field_value(d.enc, &d.words, "GLC") == Some(1) + }) +} + +pub fn automatic_plan(cfg: &Cfg, lw: &Lw, split_compute: bool, tables: usize) -> Option { + let large = large(cfg); + if !large && !(split_compute && atomic_candidate(cfg)) { return None; } + let p = plan(cfg, lw)?; + if p.words() > tables { return None; } let insts = |n: usize| cfg.blocks[p.order[n]].insts.len(); let all: usize = (0..p.order.len()).map(insts).sum(); let once: usize = p.rep.iter().map(|&n| insts(n)).sum(); - large(cfg) && once * 10 < all * 3 && p.words() <= tables + let repeated = if large { once * 10 < all * 3 } else { p.rep.len() * 4 <= p.order.len() }; + repeated.then_some(p) } -/// Whether a program is large enough for `wanted` to be asked. +/// Whether to consider compaction based on instruction count alone. pub fn large(cfg: &Cfg) -> bool { cfg.rpo.iter().map(|&b| cfg.blocks[b].insts.len()).sum::() >= 20_000 } diff --git a/crates/xcl/src/gpu/dxil/compact_tests.rs b/crates/xcl/src/gpu/dxil/compact_tests.rs index 7602b5da43..e0bb2e8935 100644 --- a/crates/xcl/src/gpu/dxil/compact_tests.rs +++ b/crates/xcl/src/gpu/dxil/compact_tests.rs @@ -5,6 +5,18 @@ use crate::gpu::rdna2::encode; use crate::gpu::recomp::runner::{self, KernelState}; use crate::gpu::recomp::KERNEL_LANES; +#[test] +fn medium_compact_candidate_requires_branching_and_a_returning_atomic() { + let candidate = |copies, glc| { + let mut code = encode("BUFFER_ATOMIC_ADD", "ENC_MUBUF", &[("GLC", glc)], None).unwrap(); + code.extend(repeated(copies)); + super::compact::atomic_candidate(&super::cfg::Cfg::build(&code).unwrap()) + }; + assert!(!candidate(1, 1)); + assert!(!candidate(100, 0)); + assert!(candidate(100, 1)); +} + fn repeated(copies: usize) -> Vec { let i = |n: &str, e: &str, f: &[(&str, u64)]| encode(n, e, f, None).unwrap_or_else(|x| panic!("{n}: {x}")); let mut v = Vec::new(); @@ -218,9 +230,8 @@ fn gpu_compact_inline_table_above_old_cap_checks_late_entries() { let cfg = super::cfg::Cfg::build(&code).unwrap(); let leaders = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect(); let lw = super::lower::Lw::new(&cfg.insts, &leaders, o, &super::kernel::Entry::Kernel); - let p = super::compact::plan(&cfg, &lw).unwrap(); + let p = super::compact::automatic_plan(&cfg, &lw, false, super::compact::TABLE_WORDS_WAVE32).unwrap(); assert!(p.inline && p.words() > 8192 && p.words() <= 12288); - assert!(super::compact::wanted(&cfg, &p, super::compact::TABLE_WORDS_WAVE32)); let k = translate_full(&code, o).unwrap(); for initial in [0u32, u32::MAX - 1, 0u32.wrapping_sub(COPIES as u32), 0u32.wrapping_sub((2 * COPIES) as u32), 0u32.wrapping_sub(COPIES as u32 + 1)] { let mut st = KernelState::default(); diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 6ef85ad800..82cf4c0905 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -74,7 +74,7 @@ pub fn dispatch_piece_limit() -> usize { std::env::var("XCL_DIRECT_SPLIT_INSTRUCTIONS").ok().and_then(|s| s.parse().ok()).unwrap_or(12_500) } -/// `XCL_DIRECT_COMPACT`: `1` forces the compact form, `0` forbids it, unset leaves it to `compact::wanted`. +/// `XCL_DIRECT_COMPACT`: `1` forces the compact form, `0` forbids it, unset uses automatic selection. pub fn compact_mode() -> Option { match std::env::var("XCL_DIRECT_COMPACT").as_deref() { Ok("1") => Some(true), @@ -278,8 +278,12 @@ fn translate_on_this_thread( } } - let plan = if (compute || kernel) && compact.unwrap_or_else(|| super::compact::large(&cfg)) { super::compact::plan(&cfg, &lw) } else { None }; - let plan = plan.filter(|p| compact.unwrap_or_else(|| super::compact::wanted(&cfg, p, tables))); + let plan = match compact { + _ if !compute && !kernel => None, + Some(false) => None, + Some(true) => super::compact::plan(&cfg, &lw), + None => super::compact::automatic_plan(&cfg, &lw, compute && split, tables), + }; if let Some(p) = &plan { crate::xlog_info!("[SHADER] direct DXIL compact form: {} blocks of {} kinds", p.order.len(), p.rep.len()); } From f8f9de654f82aba63dc80451b895ac4e49e691d6 Mon Sep 17 00:00:00 2001 From: bmjask <11672696+bmjask@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:58:17 -0500 Subject: [PATCH 3/3] Tests: measure cold compute pipelines and replay GPU outputs offline --- crates/xcl/src/gpu/dxil/module/opt.rs | 1 + crates/xcl/src/gpu/dxil/module/split.rs | 73 +++++ crates/xcl/src/gpu/recomp/pso.rs | 3 + .../gpu/recomp/pso/offline_cold_profile.rs | 296 ++++++++++++++++++ crates/xcl/src/gpu/recomp/runner.rs | 64 +++- 5 files changed, 435 insertions(+), 2 deletions(-) create mode 100644 crates/xcl/src/gpu/recomp/pso/offline_cold_profile.rs diff --git a/crates/xcl/src/gpu/dxil/module/opt.rs b/crates/xcl/src/gpu/dxil/module/opt.rs index 5e867f55a0..230a59f9f9 100644 --- a/crates/xcl/src/gpu/dxil/module/opt.rs +++ b/crates/xcl/src/gpu/dxil/module/opt.rs @@ -99,6 +99,7 @@ impl Module { match op { Op::Bin(..) | Op::Cast(..) | Op::Cmp(..) | Op::Select(..) | Op::Extract(..) | Op::Gep(..) => Cse::Dom, Op::Load(p, _) if self.is_const_global_ptr(*p) => Cse::Dom, + Op::Phi(_) if cfg!(test) && std::env::var_os("XCL_SAMPLE_PHI_CSE").is_some() => Cse::Block, Op::Call(f, _) if self.funcs[*f as usize].attrs == FnAttrs::ReadNone => Cse::Dom, Op::Call(f, _) if self.wave_call(*f) && !self.funcs[*f as usize].name.starts_with("dx.op.waveIsFirstLane") => Cse::Block, _ => Cse::No, diff --git a/crates/xcl/src/gpu/dxil/module/split.rs b/crates/xcl/src/gpu/dxil/module/split.rs index f14751b43b..7a88b9ae11 100644 --- a/crates/xcl/src/gpu/dxil/module/split.rs +++ b/crates/xcl/src/gpu/dxil/module/split.rs @@ -145,6 +145,9 @@ impl Shader { stride = stride.checked_add(words)?; } } + if cfg!(test) && std::env::var_os("XCL_SAMPLE_SLOT_REUSE").is_some() { + (stride, slots) = self.m.reuse_piece_slots(&plan, &slots)?; + } stride.checked_mul(threads[0])?.checked_mul(4)?; let pieces = (0..plan.blocks.len()).map(|i| self.make_piece(&plan, i, stride, &slots, threads, &prefix)).collect::>>()?; Some(DispatchChain { pieces, dwords_per_group: stride.checked_mul(threads[0])? }) @@ -313,6 +316,38 @@ fn inst(v: Value) -> Option { } impl Module { + fn reuse_piece_slots(&self, plan: &Plan, slots: &BTreeMap) -> Option<(u32, BTreeMap)> { + let mut stage = vec![0; self.blocks.len()]; + for (i, blocks) in plan.blocks.iter().enumerate() { + for block in blocks { stage[block.0 as usize] = i; } + } + let mut last = BTreeMap::new(); + for edge in &plan.edges { + for &v in &edge.live { + let end = last.entry(v).or_insert(0); + *end = (*end).max(stage[edge.to.0 as usize]); + } + } + let mut ranges = Vec::with_capacity(slots.len()); + for &v in slots.keys() { + let start = stage[self.def_block[inst(v)?].0 as usize]; + ranges.push((start, v, last[&v], self.transport_words(v)? as usize)); + } + ranges.sort_unstable(); + let mut occupied_until = Vec::new(); + let mut layout = BTreeMap::new(); + for (start, v, end, size) in ranges { + // A restore can be sunk to the end of its piece, so even values last + // consumed in the writer's own piece must keep separate slots. + let index = occupied_until.windows(size).position(|words| words.iter().all(|&e| e < start)) + .unwrap_or(occupied_until.len()); + occupied_until.resize(occupied_until.len().max(index + size), end); + occupied_until[index..index + size].fill(end); + layout.insert(v, u32::try_from(index + 1).ok()?); + } + Some((u32::try_from(occupied_until.len() + 1).ok()?, layout)) + } + fn global_root(&self, v: Value) -> Option { match v { Value::Global(g) => Some(g as usize), @@ -1072,6 +1107,44 @@ mod tests { assert_eq!(reference, expected, "unsplit {threads}"); let result = runner::dispatch_split(&chain, [2, 3, 2], &initial).unwrap(); assert_eq!(result, expected, "split {threads}"); + if std::env::var_os("XCL_SAMPLE_CHAIN_TIMINGS").is_some() { + for depth in [2, 128] { + let groups = [2, 3, depth]; + let words = (threads * 6 * depth) as usize; + let initial: Vec<_> = (0..words + 16).map(|i| if i < words { i as u32 + 17 } else { 0xdeadbeef }).collect(); + let mut expected = initial.clone(); + for _ in 0..9 { + for (i, v) in expected[..words].iter_mut().enumerate() { + let (scale, bias): (u32, u32) = match i % 4 { + 0 => { *v = 100_000 + i as u32; continue; } + 1 => (17, 200), + 2 => (49, 408), + _ => (33, 144), + }; + *v = v.wrapping_mul(scale).wrapping_add(bias); + } + } + let mut rows = [Vec::new(), Vec::new()]; + for round in 0..4 { + for pass in 0..2 { + let variant = (round + pass) % 2; + let samples = if variant == 0 { + runner::dispatch_timed(&whole, groups, &[], &initial, 9).unwrap() + } else { + let (out, times) = runner::dispatch_split_samples(&chain, groups, &[], &initial, u64::MAX, 9, true).unwrap(); + assert_eq!(out, expected, "timed chain {threads} at depth {depth}"); + times + }; + rows[variant].extend_from_slice(&samples[1..]); + } + } + for (variant, row) in rows.iter_mut().enumerate() { + row.sort_by(f64::total_cmp); + println!("CHAIN_TIME lanes={threads} groups={} variant={variant} n={} median_us={:.3}", 6 * depth, + row.len(), 500.0 * (row[row.len()/2 - 1] + row[row.len()/2])); + } + } + } // in slabs: single groups, a row (and a part of one), a plane, all for most in [1, 2, 3, 6, 7, 12] { let result = runner::dispatch_split_by(&chain, [2, 3, 2], &initial, most).unwrap(); diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index da4b25e5fb..b8b0cde0f1 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -15,6 +15,9 @@ use windows::Win32::Graphics::Direct3D12::*; use super::{dxc, interface, translate, Mode, Options}; use crate::gpu::xbox; +#[cfg(test)] +mod offline_cold_profile; + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Stage { Vertex, diff --git a/crates/xcl/src/gpu/recomp/pso/offline_cold_profile.rs b/crates/xcl/src/gpu/recomp/pso/offline_cold_profile.rs new file mode 100644 index 0000000000..aec4c1e077 --- /dev/null +++ b/crates/xcl/src/gpu/recomp/pso/offline_cold_profile.rs @@ -0,0 +1,296 @@ +use super::*; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Instant; +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; +use windows::Win32::Graphics::Dxgi::*; + +#[derive(serde::Deserialize)] +struct BufferReplay { + program: String, + memory: String, + positions: String, + position_byte_offset: usize, + packed_byte_offset: usize, + sgprs: Vec, + groups: [u32; 3], + vertices: usize, +} + +#[test] +fn replay_sample_dxil_forms() { + use super::super::runner; + #[derive(serde::Deserialize)] + struct Sample { + programs: Vec, + memory: std::path::PathBuf, + expected: std::path::PathBuf, + sgprs: Vec, + groups: [u32; 3], + // Some fixtures provide only the known header and guard bytes. Compare their payload + // between forms and verify that every active record writes its first output. + payload_words: Option<[usize; 2]>, + records: Option<[usize; 2]>, + reverse_input_words: Option<[usize; 2]>, + chain_program: Option, + single_dispatch: Option, + // Atomic lanes can reserve output slots in any order within their group. + unordered_group_outputs: Option<[usize; 2]>, + } + let Some(path) = std::env::var_os("XCL_SAMPLE_DXIL_FORMS") else { return }; + let path = std::path::Path::new(&path); + let sample: Sample = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap(); + let dir = path.parent().unwrap(); + let words = |path| { + let bytes = std::fs::read(dir.join(path)).unwrap(); + assert_eq!(bytes.len() % 4, 0); + bytes.chunks_exact(4).map(|w| u32::from_le_bytes(w.try_into().unwrap())).collect::>() + }; + let input = words(sample.memory); + let expected = words(sample.expected); + assert_eq!(input.len(), expected.len()); + assert!(input != expected, "fixture must exercise an observable write"); + let programs: Vec<_> = sample.programs.iter().map(|p| std::fs::read(dir.join(p)).unwrap()).collect(); + let mut times = vec![Vec::new(); programs.len()]; + let mut reference = None; + for i in 0..programs.len() { + let mut out = runner::dispatch(&programs[i], sample.groups, &sample.sgprs, &input).unwrap(); + assert_eq!(out.len(), expected.len()); + if let Some([first, lanes]) = sample.unordered_group_outputs { + assert!(lanes > 0 && sample.groups[1..] == [1, 1]); + let count = sample.groups[0] as usize * lanes; + for block in out[first..first + count].chunks_exact_mut(lanes) { + block.sort_unstable(); + } + } + for (j, (&actual, &want)) in out.iter().zip(&expected).enumerate() { + if sample.payload_words.is_some_and(|[first, end]| (first..end).contains(&j)) { continue; } + assert_eq!(actual, want, "form {i} word {j}"); + } + if let Some([first, end]) = sample.payload_words { + let [count, stride] = sample.records.unwrap(); + assert!(count > 0 && stride > 0 && first < end && end <= out.len()); + assert!(count <= (end-first)/stride); + let mut distinct = std::collections::HashSet::new(); + for record in 0..count { + let j = first + stride * record; + assert_ne!(out[j], input[j], "form {i} active payload word {j}"); + distinct.insert(&out[j..j+stride]); + } + println!("PAYLOAD form={i} written_records={count} distinct_records={}", distinct.len()); + if let Some([src, width]) = sample.reverse_input_words { + assert!(width > 0 && distinct.len() == count); + let mut permuted = input.clone(); + for n in 0..count { + let from = src + (count - 1 - n) * width; + let to = src + n * width; + permuted[to..to+width].copy_from_slice(&input[from..from+width]); + } + let reversed = runner::dispatch(&programs[i], sample.groups, &sample.sgprs, &permuted).unwrap(); + for n in 0..count { + let from = first + (count - 1 - n) * stride; + let to = first + n * stride; + assert_eq!(&reversed[to..to+stride], &out[from..from+stride], "form {i} reversed record {n}"); + } + for j in 0..expected.len() { + if !(first..end).contains(&j) { + let want = if (src..src+count*width).contains(&j) { permuted[j] } else { expected[j] }; + assert_eq!(reversed[j], want, "form {i} reversed guard or header word {j}"); + } + } + } + } + if let Some(prior) = &reference { + assert!(&out == prior, "form {i} differs from the reference dispatch"); + } else { + reference = Some(out); + } + } + if let Some(path) = &sample.chain_program { + let code = std::fs::read(dir.join(path)).unwrap(); + let c = direct_compute(&code, 0, super::super::HEAP_WINDOWS | 4, true).unwrap(); + assert!(c.dxil == programs[0] && c.samplers.is_empty()); + let chain = c.dispatch_chain.as_ref().expect("fixture should split"); + runner::profile_buffer_forms(&c.dxil, [chain, chain], sample.groups, &sample.sgprs, &input, + reference.as_ref().unwrap(), 256 << 20).unwrap(); + return; + } + let single = sample.single_dispatch == Some(true); + for round in 0..if single { 26 } else { 6 } { + for pass in 0..programs.len() { + let i = (round + pass) % programs.len(); + let row = runner::dispatch_timed(&programs[i], sample.groups, &sample.sgprs, &input, if single { 1 } else { 12 }).unwrap(); + if round >= 2 { times[i].extend_from_slice(if single { &row } else { &row[2..] }); } + } + } + for (i, times) in times.iter_mut().enumerate() { + times.sort_by(f64::total_cmp); + println!("DXIL_TIME form={i} groups={:?} n={} median_us={:.3}", sample.groups, times.len(), + 500.0 * (times[times.len()/2-1] + times[times.len()/2])); + } +} + +#[test] +fn replay_sample_buffer_chain() { + use crate::gpu::recomp::runner; + let Some(path) = std::env::var_os("XCL_SAMPLE_BUFFER_CHAIN") else { return }; + let path = std::path::Path::new(&path); + let dir = path.parent().unwrap(); + let cfg: BufferReplay = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap(); + let read = |name: &str| std::fs::read(dir.join(name)).unwrap(); + let words = |b: &[u8]| b.chunks_exact(4).map(|w| u32::from_le_bytes(w.try_into().unwrap())).collect::>(); + let mem = words(&read(&cfg.memory)); + let expected = words(&read(&cfg.positions)); + let compiled = direct_compute(&read(&cfg.program), 0, super::super::HEAP_WINDOWS | 4, true).unwrap(); + let chain = compiled.dispatch_chain.as_ref().unwrap(); + assert!(compiled.samplers.is_empty()); + let reference = runner::dispatch(&compiled.dxil, cfg.groups, &cfg.sgprs, &mem).unwrap(); + let p = cfg.position_byte_offset / 4; + let n = cfg.packed_byte_offset / 4; + assert_eq!(expected.len(), 3 * cfg.vertices); + let check = |result: &[u32]| { + for (i, (&inword, &outword)) in mem.iter().zip(result).enumerate() { + if (p..p + expected.len()).contains(&i) { + assert_eq!(outword, expected[i - p], "position word {i}"); + } else if (n..n + cfg.vertices).contains(&i) { + assert_ne!(inword, outword, "unwritten packed output {i}"); + } else { + assert_eq!(inword, outword, "unexpected write at word {i}"); + } + } + }; + check(&reference); + if let Some(dir) = std::env::var_os("XCL_SAMPLE_ALTERNATE_CHAIN") { + let dir = std::path::Path::new(&dir); + assert!(std::fs::read(dir.join("whole.dxil")).unwrap() == compiled.dxil); + let (count, words): (usize, u32) = serde_json::from_slice(&std::fs::read(dir.join("chain.json")).unwrap()).unwrap(); + let alternate = crate::gpu::dxil::kernel::DispatchChain { + pieces: (0..count).map(|i| std::fs::read(dir.join(format!("piece-{i}.dxil"))).unwrap()).collect(), + dwords_per_group: words, + }; + let budget = std::env::var("XCL_SAMPLE_SCRATCH_BYTES").ok().map(|s| s.parse().unwrap()).unwrap_or(256 << 20); + runner::profile_buffer_forms(&compiled.dxil, [chain, &alternate], cfg.groups, &cfg.sgprs, &mem, &reference, budget).unwrap(); + return; + } + let mut rows = [Vec::new(), Vec::new()]; + let most = std::env::var("XCL_SAMPLE_SCRATCH_BYTES").ok().map(|s| s.parse::().unwrap() / + (u64::from(chain.dwords_per_group) * 4)).unwrap_or(u64::MAX).max(1); + for round in 0..4 { + for k in 0..2 { + let split = (round + k) % 2; + let times = if split == 0 { + runner::dispatch_timed(&compiled.dxil, cfg.groups, &cfg.sgprs, &mem, 5).unwrap() + } else { + let (out, times) = runner::dispatch_split_samples(chain, cfg.groups, &cfg.sgprs, &mem, most, 5, true).unwrap(); + assert!(out == reference, "split output differs from whole"); + times + }; + rows[split].extend_from_slice(×[1..]); + } + } + for (variant, row) in rows.iter_mut().enumerate() { + row.sort_by(f64::total_cmp); + println!("BUFFER_TIME variant={variant} vertices={} pieces={} words_per_group={} n={} median_us={:.3}", + cfg.vertices, chain.pieces.len(), chain.dwords_per_group, row.len(), 500.0*(row[7]+row[8])); + } +} + +#[test] +fn profile_sample_cold_compute() { + let Some(path) = std::env::var_os("XCL_SAMPLE_COLD_COMPUTE") else { return }; + let bytes = std::fs::read(path).unwrap(); + let translate_start = Instant::now(); + let compiled = direct_compute(&bytes, 0, super::super::HEAP_WINDOWS | 4, true).unwrap(); + println!("TRANSLATE bytes={} ms={:.3}", compiled.dxil.len(), translate_start.elapsed().as_secs_f64() * 1000.0); + let workers: usize = std::env::var("XCL_SAMPLE_BUILD_WORKERS").unwrap_or_else(|_| "4".into()).parse().unwrap(); + assert!(workers > 0); + let use_chain = std::env::var("XCL_SAMPLE_BUILD_CHAIN").as_deref() == Ok("1"); + let chain = compiled.dispatch_chain.as_deref(); + if let Some(dir) = std::env::var_os("XCL_SAMPLE_EXPORT_CHAIN") { + let dir = std::path::Path::new(&dir); + let chain = chain.expect("sample must split"); + std::fs::create_dir_all(dir).unwrap(); + std::fs::write(dir.join("whole.dxil"), &compiled.dxil).unwrap(); + for (i, part) in chain.pieces.iter().enumerate() { + std::fs::write(dir.join(format!("piece-{i}.dxil")), part).unwrap(); + } + std::fs::write(dir.join("chain.json"), serde_json::to_vec(&(chain.pieces.len(), chain.dwords_per_group)).unwrap()).unwrap(); + return; + } + if std::env::var_os("XCL_SAMPLE_PIECE_LAYOUT").is_some() { + if let Some(chain) = chain { + println!("LAYOUT words={} pieces={} bytes={}", chain.dwords_per_group, chain.pieces.len(), + chain.pieces.iter().map(Vec::len).sum::()); + } else { + println!("LAYOUT ineligible"); + } + return; + } + let parts: Vec<&[u8]> = match (use_chain, chain) { + (true, Some(c)) => c.pieces.iter().map(Vec::as_slice).collect(), + (true, None) => { println!("PROFILE ineligible bytes={}", compiled.dxil.len()); return; } + (false, _) => vec![&compiled.dxil], + }; + for part in &parts { + crate::gpu::dxil::validate::validate(part).unwrap(); + } + let factory: IDXGIFactory6 = unsafe { CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)) }.unwrap(); + let adapter: IDXGIAdapter1 = unsafe { factory.EnumAdapterByGpuPreference(0, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE) }.unwrap(); + assert_eq!(unsafe { adapter.GetDesc1() }.unwrap().VendorId, 0x10de); + let dev = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0).unwrap(); + let cache: ID3D12Device9 = dev.cast().unwrap(); + unsafe { cache.ShaderCacheControl(D3D12_SHADER_CACHE_KIND_FLAG_IMPLICIT_DRIVER_MANAGED | + D3D12_SHADER_CACHE_KIND_FLAG_IMPLICIT_D3D_CACHE_FOR_DRIVER, D3D12_SHADER_CACHE_CONTROL_FLAG_DISABLE) }.unwrap(); + let rs = if use_chain { dispatch_chain_root_signature(&dev, &compiled.samplers) } + else { abi_root_signature_with(&dev, false, &compiled.samplers) }.unwrap(); + let imported = std::env::var_os("XCL_SAMPLE_IMPORT_PSO").map(|dir| { + (0..parts.len()).map(|i| std::fs::read(std::path::Path::new(&dir).join(format!("{i}.pso"))).unwrap()).collect::>() + }); + let mut order: Vec<_> = (0..parts.len()).collect(); + if std::env::var_os("XCL_SAMPLE_LARGEST_FIRST").is_some() { + order.sort_by_key(|&i| std::cmp::Reverse(parts[i].len())); + } + let index = AtomicUsize::new(0); + let start = Instant::now(); + let objects = std::thread::scope(|scope| { + let threads: Vec<_> = (0..workers.min(parts.len())).map(|_| scope.spawn(|| { + let mut built = Vec::new(); + loop { + let Some(&i) = order.get(index.fetch_add(1, Ordering::Relaxed)) else { break }; + let code = parts[i]; + let cached = imported.as_ref().map(|all| &all[i]); + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::ManuallyDrop::new(Some(rs.clone())), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: code.as_ptr().cast(), BytecodeLength: code.len() }, + CachedPSO: cached.map(|data| D3D12_CACHED_PIPELINE_STATE { + pCachedBlob: data.as_ptr().cast(), CachedBlobSizeInBytes: data.len(), + }).unwrap_or_default(), + ..Default::default() + }; + let part_start = Instant::now(); + let result = unsafe { dev.CreateComputePipelineState::(&desc) }; + let part_time = part_start.elapsed(); + drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); + built.push((i, result.unwrap(), part_start.duration_since(start), part_time)); + } + built + })).collect(); + threads.into_iter().flat_map(|t| t.join().unwrap()).collect::>() + }); + println!("PROFILE parts={} bytes={} wall_ms={:.2} cache=disabled", objects.len(), + parts.iter().map(|p| p.len()).sum::(), start.elapsed().as_secs_f64() * 1000.0); + for (i, _, offset, elapsed) in &objects { + println!("PIECE index={i} bytes={} start_ms={:.2} driver_ms={:.2}", parts[*i].len(), + offset.as_secs_f64() * 1000., elapsed.as_secs_f64() * 1000.); + } + if let Some(dir) = std::env::var_os("XCL_SAMPLE_EXPORT_PSO") { + let dir = std::path::Path::new(&dir); + std::fs::create_dir_all(dir).unwrap(); + for (i, object, _, _) in objects { + let blob = unsafe { object.GetCachedBlob() }.unwrap(); + let data = unsafe { std::slice::from_raw_parts(blob.GetBufferPointer().cast::(), blob.GetBufferSize()) }; + assert!(!data.is_empty()); + std::fs::write(dir.join(format!("{i}.pso")), data).unwrap(); + } + } +} diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index 2041690262..34b5c65201 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -1632,6 +1632,14 @@ pub(crate) fn dispatch_split( pub(crate) fn dispatch_split_by( chain: &crate::gpu::dxil::kernel::DispatchChain, groups: [u32; 3], mem: &[u32], most: u64, ) -> Result, String> { + dispatch_split_samples(chain, groups, &[], mem, most, 1, false).map(|(m, _)| m) +} + +#[cfg(test)] +pub(crate) fn dispatch_split_samples( + chain: &crate::gpu::dxil::kernel::DispatchChain, groups: [u32; 3], sgprs: &[u32], mem: &[u32], + most: u64, reps: usize, timed: bool, +) -> Result<(Vec, Vec), String> { let mut g = GPU.lock().unwrap(); let gpu = g.get_or_insert_with(init).as_mut().map_err(|e| e.clone())?; let rs = super::pso::dispatch_chain_root_signature(&gpu.dev, &[])?; @@ -1642,8 +1650,8 @@ pub(crate) fn dispatch_split_by( ..Default::default() }).map_err(e) }).collect::>()?; - dispatch_with(&gpu.dev, &gpu.queue, &gpu.fence, &mut gpu.value, &pieces[0], &rs, groups, &[], mem, 1, false, - Some((&pieces, chain.dwords_per_group, most))).map(|(m,_)| m) + dispatch_with(&gpu.dev, &gpu.queue, &gpu.fence, &mut gpu.value, &pieces[0], &rs, groups, sgprs, mem, reps, timed, + Some((&pieces, chain.dwords_per_group, most))) } /// `dispatch` run `reps` times in one command list (a UAV barrier between them, memory not @@ -1663,6 +1671,58 @@ pub fn dispatch_timed(dxil: &[u8], groups: [u32; 3], sgprs: &[u32], mem: &[u32], dispatch_with(&gpu.dev, &gpu.queue, &gpu.fence, &mut gpu.value, &pso, &gpu.rs, groups, sgprs, mem, reps.max(1), true, None).map(|(_, t)| t) } +#[cfg(test)] +pub(crate) fn profile_buffer_forms( + whole: &[u8], chains: [&crate::gpu::dxil::kernel::DispatchChain; 2], groups: [u32; 3], + sgprs: &[u32], mem: &[u32], expected: &[u32], budget: u64, +) -> Result<(), String> { + let mut g = GPU.lock().unwrap(); + let gpu = g.get_or_insert_with(init).as_mut().map_err(|e| e.clone())?; + let rs = super::pso::dispatch_chain_root_signature(&gpu.dev, &[])?; + let blob = std::env::var_os("XCL_SAMPLE_REPLAY_WHOLE_PSO").map(std::fs::read).transpose().map_err(|err| err.to_string())?; + let build = |code: &[u8], signature: &ID3D12RootSignature, cache: Option<&[u8]>| unsafe { + gpu.dev.CreateComputePipelineState::(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: transmute_copy(signature), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: code.as_ptr().cast(), BytecodeLength: code.len() }, + CachedPSO: cache.map(|bytes| D3D12_CACHED_PIPELINE_STATE { + pCachedBlob: bytes.as_ptr().cast(), CachedBlobSizeInBytes: bytes.len(), + }).unwrap_or_default(), + ..Default::default() + }).map_err(e) + }; + let base = build(whole, &gpu.rs, blob.as_deref())?; + let alternative = std::env::var_os("XCL_SAMPLE_ALTERNATE_WHOLE").map(|path| { + let dxil = std::fs::read(path).map_err(|err| err.to_string())?; + build(&dxil, &gpu.rs, None) + }).transpose()?; + let count = if alternative.is_some() { 1 } else { 2 }; + let pieces: Vec> = chains[..count].iter().map(|c| c.pieces.iter().map(|p| build(p, &rs, None)).collect::>()).collect::>()?; + let mut samples = [Vec::new(), Vec::new(), Vec::new()]; + for round in 0..12 { + for pass in 0..3 { + let variant = (round / 2 + if round % 2 == 0 { pass } else { 2 - pass }) % 3; + let whole = match variant { 0 => Some(&base), 2 => alternative.as_ref(), _ => None }; + let (pso, signature, chain) = if let Some(pso) = whole { (pso, &gpu.rs, None) } else { + let i = variant - 1; + let words = chains[i].dwords_per_group; + let most = (budget / (u64::from(words) * 4)).max(1); + (&pieces[i][0], &rs, Some((pieces[i].as_slice(), words, most))) + }; + let (out, times) = dispatch_with(&gpu.dev, &gpu.queue, &gpu.fence, &mut gpu.value, pso, signature, + groups, sgprs, mem, 12, true, chain)?; + if out != expected { return Err(format!("replay readback differs for form {variant}")); } + if round >= 3 { samples[variant].extend_from_slice(×[2..]); } + } + } + for (i, row) in samples.iter_mut().enumerate() { + row.sort_by(f64::total_cmp); + let mid = row.len() / 2; + println!("FORM_TIME form={i} groups={groups:?} budget={budget} n={} median_us={:.3} p90_us={:.3}", + row.len(), 500.0 * (row[mid-1]+row[mid]), row[row.len()*9/10]*1000.0); + } + Ok(()) +} + /// Dispatch with an existing compute pipeline on `dev` (its own queue), e.g. one the D3D12.X /// backend built from a console shader: root signature `rs` with the XCL shader ABI, u0 = /// `sgprs`, u2 = `mem`. Returns the memory afterwards.