From af21d7773852abf88b1c1b8c423c133c8378518b Mon Sep 17 00:00:00 2001 From: ettehn <141814824+ettehn@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:12:14 +0800 Subject: [PATCH] Shaders: trace offline precompile phases Extend XCL_PSO_TRACE to identify whether offline precompile is in translation, waiting for a slot, reading the driver cache, or inside pipeline creation. Pair the boundaries by span and include process private commit for diagnosing stalled workers. --- README.md | 5 ++ crates/xcl/src/shaders.rs | 111 ++++++++++++++++++++++++++++++-------- 2 files changed, 95 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 1bd0c54868..10bcf11cb9 100644 --- a/README.md +++ b/README.md @@ -291,6 +291,11 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder `XCL_PSO_TRACE=1` logs every driver compile. A huge compute program the driver refuses is logged with the driver's verdict (`the driver refused the compute PSO of record HASH … with 0x…`): its dispatches are skipped. +- For `xcl shaders --precompile` and shader exports, `XCL_PSO_TRACE=1` also logs phase + boundaries, elapsed time, and process private memory. Match start and end by + `span`; per-record lines also include the shader hash. + Offline and launch preparation pipeline traces distinguish cache reads, waiting for a + worker slot, and D3D12 pipeline creation with or without a cached blob. - With `XCL_DRED=1`, a D3D12 device removal logs GPU breadcrumbs in `xcl.log`. XCL examines up to 4,096 command lists and reports up to 64 unfinished lists, starting with those on which the GPU completed at least one operation. For each, it names the translated diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 4c5a014974..b293ebc453 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -702,6 +702,48 @@ impl Agg { } } +/// Opt-in boundaries for diagnosing a precompile that stalls before its progress counter. +struct ShaderPhase { + id: u64, + name: &'static str, + record: Option, + bytes: usize, + start: std::time::Instant, +} + +impl ShaderPhase { + fn enabled() -> bool { + static TRACE: std::sync::OnceLock = std::sync::OnceLock::new(); + *TRACE.get_or_init(|| std::env::var("XCL_PSO_TRACE").is_ok_and(|v| v.trim() == "1")) + } + + fn start(name: &'static str, record: Option, bytes: usize) -> Option { + if !Self::enabled() { return None; } + static NEXT_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + let id = NEXT_ID.fetch_add(1, Ordering::Relaxed); + let phase = Self { id, name, record, bytes, start: std::time::Instant::now() }; + phase.log("start"); + Some(phase) + } + + fn log(&self, boundary: &str) { + use windows_sys::Win32::System::{ProcessStatus, Threading}; + let mut memory: ProcessStatus::PROCESS_MEMORY_COUNTERS_EX = unsafe { std::mem::zeroed() }; + memory.cb = std::mem::size_of_val(&memory) as u32; + let sampled = unsafe { + ProcessStatus::K32GetProcessMemoryInfo(Threading::GetCurrentProcess(), (&mut memory as *mut ProcessStatus::PROCESS_MEMORY_COUNTERS_EX).cast(), memory.cb) + } != 0; + let private = if sampled { (memory.PrivateUsage >> 20).to_string() } else { "-".to_string() }; + let record = self.record.map_or_else(|| "-".to_string(), |hash| format!("{hash:016x}")); + eprintln!("shader phase {boundary} {} span={} record={record} bytes={} elapsed_ms={} private_mib={private}", + self.name, self.id, self.bytes, self.start.elapsed().as_millis()); + } +} + +impl Drop for ShaderPhase { + fn drop(&mut self) { self.log("end"); } +} + enum Input { Pack { data: Vec, records: Vec }, Files(Vec), @@ -936,7 +978,10 @@ pub fn run(path: &Path, args: &[String]) -> i32 { let n = files.len(); (Input::Files(files), format!("folder, {n} files")) } else { - let data = match std::fs::read(path) { + let data = match { + let _phase = ShaderPhase::start("input-read", None, 0); + std::fs::read(path) + } { Ok(d) => d, Err(e) => { eprintln!("xcl shaders: {}: {e}", path.display()); @@ -944,7 +989,10 @@ pub fn run(path: &Path, args: &[String]) -> i32 { } }; if data.starts_with(pack::RPF9_MAGIC) { - let records = pack::scan(&data, 0x40); + let records = { + let _phase = ShaderPhase::start("pack-scan", None, data.len()); + pack::scan(&data, 0x40) + }; let what = format!("RPF9 package {:.1} MB, {} shader records", data.len() as f64 / 1048576.0, records.len()); (Input::Pack { data, records }, what) } else if opts.export_hlsl.is_some() || opts.measure_pso.is_some() { @@ -1062,7 +1110,10 @@ fn export_hlsl(input: &Input, dir: &Path, min_kb: usize, count: usize, windows: continue; } matched = true; - let hlsl = match recomp::pso::console_hlsl(&blob, recomp::pso::Stage::Compute, windows, split) { + let hlsl = match { + let _phase = ShaderPhase::start("export-translate", Some(hash), blob.len()); + recomp::pso::console_hlsl(&blob, recomp::pso::Stage::Compute, windows, split) + } { Ok((hlsl, _)) => hlsl, Err(e) => { failures += 1; @@ -1276,7 +1327,7 @@ mod pipeline_cap_tests { pipelines.max_dxil = dxil.len() - 1; let start = Instant::now(); - pipelines.make_with_cache_path(&recomp::pso::Compiled { dispatch_chain: None, dxil: dxil.clone(), samplers: vec![] }, Some(path.clone())); + pipelines.make_with_cache_path(&recomp::pso::Compiled { dispatch_chain: None, dxil: dxil.clone(), samplers: vec![] }, Some(path.clone()), None); let elapsed = start.elapsed(); let capped = pipelines.capped.load(Ordering::Relaxed); let made = pipelines.made.load(Ordering::Relaxed); @@ -1360,7 +1411,7 @@ mod pipeline_cap_tests { }; pipelines.max_dxil = max_piece; - pipelines.make(&compiled); + pipelines.make(&compiled, None); let p0_path = scratch.0.join(driver_cache::name_for(&piece0, 0, true)); let p1_path = scratch.0.join(driver_cache::name_for(&piece1, 0, true)); let whole_path = scratch.0.join(driver_cache::name_for(&whole, 0, false)); @@ -1375,7 +1426,7 @@ mod pipeline_cap_tests { assert!(!whole_path.exists(), "unsplit whole .pso should not be written for a split compute program"); // Second pass reuses both cached piece blobs. - pipelines.make(&compiled); + pipelines.make(&compiled, None); assert_eq!(pipelines.reused.load(Ordering::Relaxed), 2); assert_eq!(pipelines.made.load(Ordering::Relaxed), 4); assert_eq!(pipelines.refused.load(Ordering::Relaxed), 0); @@ -1401,7 +1452,7 @@ mod pipeline_cap_tests { std::fs::write(&p1_path, b"corrupt chain blob").expect("corrupt piece1 blob"); pipelines.max_dxil = piece1.len() - 1; let reused_before = pipelines.reused.load(Ordering::Relaxed); - pipelines.make(&compiled); + pipelines.make(&compiled, None); assert!(!p1_path.exists(), "rejected over-cap .chain.pso should be removed"); assert_eq!(pipelines.capped.load(Ordering::Relaxed), 1); if piece0.len() <= pipelines.max_dxil { @@ -1454,11 +1505,12 @@ impl Pipelines { /// into a dispatch chain of at least two pieces, each piece is built and cached under the /// dispatch-chain root signature (`.chain.pso`) as the runtime does (`dispatch_chain::build`), /// instead of the unsplit whole container. - fn make(&self, c: &recomp::pso::Compiled) { - self.make_with_cache_path(c, None); + fn make(&self, c: &recomp::pso::Compiled, record: Option) { + let _phase = ShaderPhase::start("precompile-pipeline", record, c.dxil.len()); + self.make_with_cache_path(c, None, record); } - fn make_with_cache_path(&self, c: &recomp::pso::Compiled, path_override: Option) { + fn make_with_cache_path(&self, c: &recomp::pso::Compiled, path_override: Option, record: Option) { if path_override.is_none() { if let Some(chain) = c.dispatch_chain.as_deref().filter(|chain| chain.pieces.len() >= 2) { self.split_programs.fetch_add(1, Ordering::Relaxed); @@ -1466,7 +1518,7 @@ impl Pipelines { let workers = chain.pieces.len().min(self.most); if workers <= 1 { for piece in &chain.pieces { - self.make_one(piece, &c.samplers, true, None); + self.make_one(piece, &c.samplers, true, None, record); } } else { let next = AtomicUsize::new(0); @@ -1475,7 +1527,7 @@ impl Pipelines { s.spawn(|| loop { let i = next.fetch_add(1, Ordering::Relaxed); let Some(piece) = chain.pieces.get(i) else { break }; - self.make_one(piece, &c.samplers, true, None); + self.make_one(piece, &c.samplers, true, None, record); }); } }); @@ -1483,10 +1535,10 @@ impl Pipelines { return; } } - self.make_one(&c.dxil, &c.samplers, false, path_override); + self.make_one(&c.dxil, &c.samplers, false, path_override, record); } - fn make_one(&self, dxil: &[u8], samplers: &[recomp::pso::StaticSampler], chained: bool, path_override: Option) { + fn make_one(&self, dxil: &[u8], samplers: &[recomp::pso::StaticSampler], chained: bool, path_override: Option, record: Option) { use windows::Win32::Graphics::Direct3D12::*; let key: (bool, Vec) = (chained, samplers.iter().flat_map(|(w, cmp)| w.iter().copied().chain([*cmp as u32])).collect()); let rs = { @@ -1525,7 +1577,10 @@ impl Pipelines { } driver_cache::path_for(dxil, desc.Flags.0, chained) }); - let cached = path.as_deref().and_then(driver_cache::load); + let cached = { + let _phase = ShaderPhase::start("pipeline-cache-read", record, dxil.len()); + path.as_deref().and_then(driver_cache::load) + }; let over_cap = self.max_dxil != 0 && dxil.len() > self.max_dxil; // over the cap and no blob from an earlier run: the driver's compile of this one takes // tens of minutes and gigabytes; the pass finishes without it, and the runtime builds it @@ -1537,6 +1592,7 @@ impl Pipelines { return; } { + let _phase = ShaderPhase::start("pipeline-slot", record, dxil.len()); let mut n = self.running.0.lock().unwrap(); while *n >= self.most { n = self.running.1.wait(n).unwrap(); @@ -1547,8 +1603,11 @@ impl Pipelines { desc.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: bytes.as_ptr().cast(), CachedBlobSizeInBytes: bytes.len() }; // a driver that cannot use the blob may compile from the DXIL itself and still // return Ok: only the pipeline carrying a blob of the size we handed over is a hit - unsafe { self.dev.CreateComputePipelineState::(&desc) } - .ok() + let pso = { + let _phase = ShaderPhase::start("pipeline-create-with-blob", record, dxil.len()); + unsafe { self.dev.CreateComputePipelineState::(&desc) } + }; + pso.ok() .filter(|pso| unsafe { pso.GetCachedBlob() }.is_ok_and(|b| unsafe { b.GetBufferSize() } == bytes.len())) }); // A stale blob is not a usable cache hit. Do not let its presence bypass the offline @@ -1569,7 +1628,10 @@ impl Pipelines { Ok(pso) } else { desc.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); - let pso = unsafe { self.dev.CreateComputePipelineState::(&desc) }; + let pso = { + let _phase = ShaderPhase::start("pipeline-create-without-blob", record, dxil.len()); + unsafe { self.dev.CreateComputePipelineState::(&desc) } + }; if let (Some(path), Ok(pso)) = (path.as_deref(), &pso) { if let Ok(blob) = unsafe { pso.GetCachedBlob() } { let bytes = unsafe { blob.GetBufferPointer() }.cast::(); @@ -1653,6 +1715,7 @@ pub(crate) fn prepare_for_launch(root: &Path, progress: &LaunchPreparation) -> R } fn precompile(input: &Input, limit: usize, windows: u32, split: Option, only: Option<&str>, pipelines: bool, used: Option<&std::collections::HashSet>, t0: std::time::Instant, startup: Option<&LaunchPreparation>) -> Result<(), String> { + let adapter_init = ShaderPhase::start("precompile-init", None, 0); let pipelines = if pipelines { let mut p = Pipelines::for_adapter(startup.map_or("auto", |p| p.adapter.as_str())) .map_err(|e| format!("No pipeline device: {e}"))?; @@ -1681,6 +1744,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on let startup_device = pipelines.filter(|_| startup.is_some()); let graphics_split = split.unwrap_or_else(|| startup_device.map_or_else(recomp::runner::graphics_wave32, |p| recomp::pso::graphics_wave32_for_device(&p.dev))); let split = split.unwrap_or_else(|| startup_device.map_or_else(|| recomp::pso::split_wave64_forced() || recomp::runner::wave64_supported().is_ok_and(|w| !w), |p| recomp::pso::wave32_only_for_device(&p.dev))); + drop(adapter_init); println!( "precompiling {n} shaders into {} ({} compile threads; {} memory windows{}{})", recomp::dxc::cache_dir().display(), @@ -1727,12 +1791,17 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on record_done(); continue; } - match recomp::pso::console_to_dxil_in(&blob, recomp::pso::Stage::Compute, 0, split, windows) { + let record = ShaderPhase::enabled().then(|| shader::fnv64(&blob)); + let translated = { + let _phase = ShaderPhase::start("precompile-translate", record, blob.len()); + recomp::pso::console_to_dxil_in(&blob, recomp::pso::Stage::Compute, 0, split, windows) + }; + match translated { Ok(c) => { if let Some(p) = pipelines { - p.make(&c); + p.make(&c, record); if startup.is_some() && c.dispatch_chain.as_ref().is_some_and(|plan| plan.pieces.len() >= 2) { - p.make_one(&c.dxil, &c.samplers, true, None); + p.make_one(&c.dxil, &c.samplers, true, None, record); } } compiled.fetch_add(1, Ordering::Relaxed)