From c65e2c8b459dd4ac45ff427b3e89abbb5ef707df Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 11:08:23 -0500 Subject: [PATCH] Shaders: --precompile --processes N builds in N processes NVIDIA's driver builds about one compute pipeline at a time in a process, however many threads ask: on an RTX 4090 (driver 621.24) --pipelines with 12 pipeline threads kept 2 threads busy at 28 % CPU. Four processes, each with every fourth record and the shared DXIL and driver-blob caches, made about 3.7x the driver blobs in the same time. --processes N starts N copies of xcl shaders with --shard k/N (records k, k + N, ...), gives each its share of the DXC threads and 2 pipeline threads unless XCL_DXC_THREADS / XCL_PIPELINE_THREADS are set, and returns the first failing process's exit code. Assisted-by: Claude Code (Claude Opus 5.5) Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + crates/xcl/src/shaders.rs | 110 +++++++++++++++++++++++++++- crates/xcl/tests/gpu_compute_e2e.rs | 35 +++++++++ 3 files changed, 142 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 722483312..c2faaebcf 100644 --- a/README.md +++ b/README.md @@ -115,6 +115,7 @@ xcl run D:\Game [-- game arguments] # run xcl disasm [--hex] # RDNA2 disassembler (console containers too) xcl shaders D:\data\shaders.rpf --top 50 # pack statistics; --recomp / --compile N xcl shaders D:\data\shaders.rpf --precompile --only cs --pipelines # build compute pipelines and save driver blobs for the next run + # --processes N: in N processes (NVIDIA builds about one pipeline at a time per process) xcl rpf D:\data\shaders.rpf --extract NAME --out folder ``` diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index db0c70049..2426e1235 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -688,6 +688,17 @@ pub fn run(path: &Path, args: &[String]) -> i32 { let _ = EXAMPLE_FOR.set(m.clone()); } let t0 = std::time::Instant::now(); + let shard = match args.iter().position(|a| a == "--shard").map(|i| args.get(i + 1).and_then(|v| parse_shard(v))) { + Some(None) => { + eprintln!("xcl shaders: --shard takes k/n with k < n"); + return 2; + } + Some(Some(s)) => Some(s), + None => None, + }; + if let Some(n) = opt("--processes").filter(|&n| n > 1 && shard.is_none() && args.iter().any(|a| a == "--precompile")) { + return precompile_in_processes(path, args, n, t0); + } let (input, what) = if path.is_dir() { let mut files = Vec::new(); @@ -715,13 +726,82 @@ pub fn run(path: &Path, args: &[String]) -> i32 { if args.iter().any(|a| a == "--precompile") { let only = args.iter().position(|a| a == "--only").and_then(|i| args.get(i + 1)).map(|s| s.to_ascii_lowercase()); let pipelines = args.iter().any(|a| a == "--pipelines"); - return precompile(&input, opt("--limit").unwrap_or(usize::MAX), opt("--windows").unwrap_or(4) as u32, opt("--split").map(|v| v != 0), only.as_deref(), pipelines, t0); + return precompile(&input, opt("--limit").unwrap_or(usize::MAX), opt("--windows").unwrap_or(4) as u32, opt("--split").map(|v| v != 0), only.as_deref(), pipelines, shard, t0); } let agg = analyze(&input, recomp_on, compile, iface_on); drop(input); print(path, &what, agg, top, json, t0, compile) } +/// `--shard k/n`: this process takes records k, k + n, k + 2n, … +fn parse_shard(v: &str) -> Option<(usize, usize)> { + let (k, n) = v.split_once('/')?; + let (k, n) = (k.trim().parse().ok()?, n.trim().parse::().ok()?); + (n > 0 && k < n).then_some((k, n)) +} + +/// The arguments of process `k` of `n`: the caller's, without `--processes N`, with `--shard k/n`. +fn shard_args(args: &[String], k: usize, n: usize) -> Vec { + let mut out = Vec::with_capacity(args.len() + 2); + let mut i = 0; + while i < args.len() { + if args[i] == "--processes" { + i += 2; + continue; + } + out.push(args[i].clone()); + i += 1; + } + out.push("--shard".into()); + out.push(format!("{k}/{n}")); + out +} + +/// `--precompile --processes N`: N processes of this program, each with `--shard k/N`, sharing +/// the DXIL and driver-blob caches. NVIDIA's driver builds about one pipeline at a time in a +/// process however many threads ask (an RTX 4090: 2 threads busy, 28 % CPU with 12 pipeline +/// threads; four processes made ~3.7× the pipelines). Each gets its share of the DXC threads +/// and 2 pipeline threads unless `XCL_DXC_THREADS` / `XCL_PIPELINE_THREADS` say otherwise. +/// Returns the first failing process's code (0: all finished). +fn precompile_in_processes(path: &Path, args: &[String], n: usize, t0: std::time::Instant) -> i32 { + let exe = match std::env::current_exe() { + Ok(e) => e, + Err(e) => { + eprintln!("xcl shaders --processes: {e}"); + return 2; + } + }; + let dxc = (recomp::dxc::compile_threads() / n).max(1).to_string(); + println!("precompiling in {n} processes ({dxc} DXC threads each)"); + let mut children = Vec::new(); + for k in 0..n { + let mut c = std::process::Command::new(&exe); + c.arg("shaders").arg(path).args(shard_args(args, k, n)); + if std::env::var_os("XCL_DXC_THREADS").is_none() { + c.env("XCL_DXC_THREADS", &dxc); + } + if std::env::var_os("XCL_PIPELINE_THREADS").is_none() { + c.env("XCL_PIPELINE_THREADS", "2"); + } + match c.spawn() { + Ok(ch) => children.push((k, ch)), + Err(e) => eprintln!("xcl shaders --processes: process {k}: {e}"), + } + } + let mut code = if children.len() == n { 0 } else { 2 }; + for (k, mut ch) in children { + let c = ch.wait().map(|s| s.code().unwrap_or(1)).unwrap_or(1); + if c != 0 { + eprintln!("xcl shaders --processes: process {k} of {n} ended with {c}"); + if code == 0 { + code = c; + } + } + } + println!("{n} processes done ({:.0} s)", t0.elapsed().as_secs_f64()); + code +} + /// `--precompile`: translate every VS / PS / MS / CS program and compile it into the DXIL cache /// (`recomp::dxc::cache_dir()`), the same HLSL the runtime will ask for, so a title does not /// wait for DXC on first use. Resumable: cached programs are skipped. GS halves need their @@ -834,7 +914,7 @@ impl Pipelines { } } -fn precompile(input: &Input, limit: usize, windows: u32, split: Option, only: Option<&str>, pipelines: bool, t0: std::time::Instant) -> i32 { +fn precompile(input: &Input, limit: usize, windows: u32, split: Option, only: Option<&str>, pipelines: bool, shard: Option<(usize, usize)>, t0: std::time::Instant) -> i32 { let pipelines = if pipelines { match Pipelines::new() { Ok(p) => Some(p), @@ -860,10 +940,11 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on let graphics_split = split.unwrap_or_else(recomp::runner::graphics_wave32); let split = split.unwrap_or_else(|| recomp::pso::split_wave64_forced() || recomp::runner::wave64_supported().is_ok_and(|w| !w)); println!( - "precompiling {n} shaders into {} ({} compile threads; {windows} memory windows{})", + "precompiling {n} shaders into {} ({} compile threads; {windows} memory windows{}{})", recomp::dxc::cache_dir().display(), recomp::dxc::compile_threads(), - if split { ", split wave64 for a GPU with 32-lane waves" } else { "" } + if split { ", split wave64 for a GPU with 32-lane waves" } else { "" }, + shard.map_or(String::new(), |(k, m)| format!("; records {k}, {k} + {m}, … (--shard {k}/{m})")) ); std::thread::scope(|s| { for _ in 0..threads { @@ -872,6 +953,11 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on if i >= n { break; } + // another process's record (`--shard`) + if shard.is_some_and(|(k, m)| i % m != k) { + done.fetch_add(1, Ordering::Relaxed); + continue; + } let (name, blob) = input.get(i); let Some(blob) = blob else { continue }; let Some(sh) = xbox::parse(&blob) else { continue }; @@ -1256,6 +1342,22 @@ mod tests { use super::*; use crate::gpu::xbox::tests::{fssm, sample, CODE}; + #[test] + fn shards_split_the_records_and_drop_processes() { + assert_eq!(parse_shard("1/4"), Some((1, 4))); + assert_eq!(parse_shard(" 0 / 2 "), Some((0, 2))); + assert_eq!(parse_shard("4/4"), None); + assert_eq!(parse_shard("0/0"), None); + assert_eq!(parse_shard("x"), None); + let args: Vec = ["--precompile", "--processes", "3", "--only", "cs", "--pipelines"].iter().map(|s| s.to_string()).collect(); + assert_eq!(shard_args(&args, 2, 3), ["--precompile", "--only", "cs", "--pipelines", "--shard", "2/3"]); + // every record in exactly one shard + let n = 3; + for i in 0..20 { + assert_eq!((0..n).filter(|&k| i % n == k).count(), 1); + } + } + #[test] fn aggregates_console_shaders() { let mut a = Agg::default(); diff --git a/crates/xcl/tests/gpu_compute_e2e.rs b/crates/xcl/tests/gpu_compute_e2e.rs index 7b9a2490e..eedc10c67 100644 --- a/crates/xcl/tests/gpu_compute_e2e.rs +++ b/crates/xcl/tests/gpu_compute_e2e.rs @@ -124,6 +124,41 @@ fn offline_compute_pipeline_is_reused_by_a_second_process() { assert!(warm.contains("pipelines loaded from the driver cache 1"), "{warm}"); } +/// `--processes 2`: two processes of `xcl shaders`, each building the pipelines of its share +/// of the records into the shared driver-blob cache. +#[test] +fn offline_compute_pipelines_split_over_processes() { + use std::{fs, process::Command}; + let _serial = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + if xcl::gpu::recomp::dxc::location().is_err() { + runner::skip_test("no DXC"); + return; + } + if runner::wave64_programs_supported() != Ok(true) { + runner::skip_test("no GPU with 32- or 64-lane waves"); + return; + } + let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let dir = std::env::temp_dir().join(format!("xcl-offline-pso-procs-{}-{nonce}", std::process::id())); + let input = dir.join("input"); + let cache = dir.join("cache"); + fs::create_dir_all(&input).unwrap(); + // two programs (other group sizes: other DXIL) + fs::write(input.join("a.bin"), console_cs(&program(), 2 << 1 | 1 << 7 | 1 << 8 | 1 << 11, [16, 8, 1])).unwrap(); + fs::write(input.join("b.bin"), console_cs(&program(), 2 << 1 | 1 << 7 | 1 << 8 | 1 << 11, [16, 4, 1])).unwrap(); + let out = Command::new(env!("CARGO_BIN_EXE_xcl")).arg("shaders").arg(&input) + .args(["--precompile", "--pipelines", "--processes", "2"]).env("XCL_DXIL_CACHE", &cache) + .env("XCL_PSO_DISK_CACHE", "1").output().unwrap(); + let text = String::from_utf8_lossy(&out.stdout).into_owned(); + let blobs = fs::read_dir(cache.join("driver")).map(|d| d.flatten().filter(|e| e.path().extension().is_some_and(|x| x == "pso")).count()).unwrap_or(0); + let _ = fs::remove_dir_all(&dir); + assert!(out.status.success(), "{text} +{}", String::from_utf8_lossy(&out.stderr)); + assert!(text.contains("precompiling in 2 processes") && text.contains("(--shard 0/2)") && text.contains("(--shard 1/2)"), "{text}"); + assert_eq!(text.matches("pipelines made on the GPU 1, refused 0").count(), 2, "{text}"); + assert_eq!(blobs, 2, "{text}"); +} + /// 16×8 threads per group (two wave64s), s[0:1] = output base and row width, TGID_X/Y in /// s2/s3, thread ids in v0/v1: each thread writes its global (x, y), and through LDS + /// s_barrier the (x, y) of the thread at the mirrored index, which is in the other wave.