Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -315,7 +315,8 @@ Fill the reusable DXIL cache ahead of a run with the read-only package wrapper.
require a first-use compile during play.
- 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.
or the driver rejects it, XCL builds the split pieces. Startup preparation builds that whole
blob, and builds the pieces only when the whole cannot be built or kept.
- A split program first seen through `ExecuteIndirect` is also kept in
`used-indirect-split.txt` beside the DXIL cache. A later `--pipelines --used-only` pass still
builds its direct-dispatch pieces and whole fallback, and additionally saves both its pieces and
Expand Down
129 changes: 125 additions & 4 deletions crates/xcl/src/shaders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1590,6 +1590,13 @@ fn split_piece_roots(prewarm_indirect: bool) -> &'static [PipelineRoot] {
}
}

/// Whether startup preparation builds a split program's dispatch chain once its whole form was
/// tried: not when the whole was built and its driver blob is on disk. The runtime then takes the
/// whole (`CachedWhole`) and never builds the chain, for direct and indirect dispatches alike.
fn chain_needed(whole_built: bool, blob_on_disk: bool) -> bool {
!(whole_built && blob_on_disk)
}

fn split_whole_roots(prewarm_indirect: bool) -> &'static [PipelineRoot] {
if prewarm_indirect {
&[PipelineRoot::DirectChain, PipelineRoot::IndirectChain]
Expand Down Expand Up @@ -2235,6 +2242,100 @@ mod pipeline_cap_tests {
assert_eq!(pipelines.reused.load(Ordering::Relaxed), reused_before + 1);
}
}

#[test]
fn a_split_programs_chain_is_prepared_only_without_its_whole() {
use super::chain_needed;
assert!(!chain_needed(true, true), "the runtime takes the whole");
assert!(chain_needed(true, false), "built but not kept: the runtime would not find it");
assert!(chain_needed(false, false), "refused or over the cap");
assert!(chain_needed(false, true), "a blob the build did not take");
}

/// Startup preparation (`prepare_compiled_compute`) of a split program builds its whole once,
/// under the ABI root, and no chain; with the whole over the cap it builds the pieces instead.
#[test]
fn startup_preparation_builds_a_split_programs_whole_and_no_chain() {
use super::{Pipelines, recomp};
use crate::hle::d3d12x::real::driver_cache;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
let _serial = crate::shaders::pipeline_library::BUILD_TEST.lock().unwrap_or_else(|e| e.into_inner());

struct Scratch(std::path::PathBuf);
impl Drop for Scratch {
fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); }
}
if let Err(reason) = recomp::dxc::location() {
recomp::runner::skip_test(&format!("no DXC: {reason}"));
return;
}
let mut pipelines = match Pipelines::new() {
Ok(pipelines) => pipelines,
Err(reason) => {
recomp::runner::skip_test(&format!("no D3D12 device: {reason}"));
return;
}
};
let compile = |src: &str| recomp::dxc::compile(src, "main", "cs_6_6", &[]).expect("DXC compile");
let piece = |n: u32| compile(&format!(
"RWByteAddressBuffer mem : register(u2); RWByteAddressBuffer sc : register(u0, space2); \
cbuffer ch : register(b0, space2) {{ uint4 meta; }}; \
[numthreads(1,1,1)] void main() {{ sc.Store(0, meta.w + {n}); mem.Store({}, meta.x); }}", n * 4));
let (piece0, piece1) = (piece(1), piece(2));
let whole = compile(
"RWByteAddressBuffer mem : register(u2); \
[numthreads(1,1,1)] void main() { \
uint x = mem.Load(0); uint y = mem.Load(4); uint z = mem.Load(8); uint w = mem.Load(12); \
mem.Store(0, x ^ y ^ z ^ w ^ 0x12345678u); mem.Store(4, (x + y) * (z + w) + 7u); \
mem.Store(8, (x * 3u) ^ (y * 5u) ^ (z * 7u)); mem.Store(12, x + y + z + w); \
uint a = mem.Load(16); uint b = mem.Load(20); uint c = mem.Load(24); uint d = mem.Load(28); \
mem.Store(16, (a ^ x) * (b + y) + 11u); mem.Store(20, (c * 13u) ^ (d + z) ^ w); \
mem.Store(24, (a + b + c + d) * 17u); mem.Store(28, (a * b) ^ (c * d) ^ 0x9e3779b9u); }",
);
let compiled = recomp::pso::Compiled {
dispatch_chain: Some(Arc::new(crate::gpu::dxil::kernel::DispatchChain {
pieces: vec![piece0.clone(), piece1.clone()],
dwords_per_group: 4,
})),
dxil: whole.clone(),
samplers: vec![],
dispatch_remap: None,
};
let blobs = |dir: &std::path::Path| {
let mut names: Vec<String> = std::fs::read_dir(dir).unwrap()
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
.filter(|n| n.ends_with(".pso"))
.collect();
names.sort();
names
};
let nonce = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos();
let scratch = |side: &str| {
let dir = std::env::temp_dir().join(format!("xcl-prep-whole-{side}-{}-{nonce}", std::process::id()));
std::fs::create_dir(&dir).expect("scratch cache directory");
Scratch(dir)
};

// the whole is built and kept: nothing else, an indirect dispatch included
let kept = scratch("kept");
pipelines.cache_dir = Some(kept.0.clone());
pipelines.max_dxil = 0;
for prewarm_indirect in [false, true] {
pipelines.prepare_compiled_compute(&compiled, prewarm_indirect).expect("prepared");
assert_eq!(blobs(&kept.0), [driver_cache::name_for(&whole, 0, false)], "the whole only (indirect: {prewarm_indirect})");
}

// the whole over the cap: the record is prepared with its pieces, and no whole is tried again
let capped = scratch("capped");
pipelines.cache_dir = Some(capped.0.clone());
pipelines.max_dxil = piece0.len().max(piece1.len());
assert!(whole.len() > pipelines.max_dxil);
pipelines.prepare_compiled_compute(&compiled, false).expect("prepared with its chain");
let mut want = vec![driver_cache::name_for(&piece0, 0, true), driver_cache::name_for(&piece1, 0, true)];
want.sort();
assert_eq!(blobs(&capped.0), want, "the pieces only");
}
}

// D3D12 devices and root signatures are free-threaded
Expand Down Expand Up @@ -2331,16 +2432,36 @@ impl Pipelines {
let make = |dxil: &[u8], root| {
self.make_required(dxil, &program.samplers, root, None, true)
};
make(&program.dxil, PipelineRoot::Whole)?;
if let Some(chain) = program.dispatch_chain.as_deref().filter(|c| c.pieces.len() >= 2) {
for &root in split_piece_roots(prewarm_indirect) {
self.make_chain_pieces_required(&chain.pieces, &program.samplers, root)?;
let whole = make(&program.dxil, PipelineRoot::Whole);
let Some(chain) = program.dispatch_chain.as_deref().filter(|c| c.pieces.len() >= 2) else { return whole };
let on_disk = whole.is_ok() && self.whole_blob_path(&program.dxil, &program.samplers).is_some_and(|p| p.is_file());
if !chain_needed(whole.is_ok(), on_disk) {
return Ok(());
}
if let Err(e) = &whole {
crate::xlog_info!("Shader preparation: {e}; the program's dispatch chain is prepared instead");
}
for &root in split_piece_roots(prewarm_indirect) {
self.make_chain_pieces_required(&chain.pieces, &program.samplers, root)?;
// (a whole refused or over the cap under the ABI root is that under a chain root too)
if whole.is_ok() {
make(&program.dxil, root)?;
}
}
Ok(())
}

/// Where `make_required` keeps the driver blob of `dxil` under the ABI root: the blob the
/// runtime's `CachedWhole` loads for a split program.
fn whole_blob_path(&self, dxil: &[u8], samplers: &[recomp::pso::StaticSampler]) -> Option<PathBuf> {
use crate::hle::d3d12x::real::driver_cache;
#[cfg(test)]
if let Some(dir) = self.cache_dir.as_deref() {
return Some(dir.join(driver_cache::name_for_root(dxil, 0, false, samplers)));
}
driver_cache::path_for_root(dxil, 0, false, samplers)
}

fn make_chain_pieces_required(&self, pieces: &[Vec<u8>], samplers: &[recomp::pso::StaticSampler],
root: PipelineRoot) -> Result<(), String> {
let workers = required_piece_workers(pieces.len(), root);
Expand Down
104 changes: 73 additions & 31 deletions crates/xcl/tests/gpu_compute_e2e.rs
Original file line number Diff line number Diff line change
Expand Up @@ -308,12 +308,34 @@ fn offline_split_compute_pipeline_is_reused_by_a_second_process() {
let _ = fs::remove_dir_all(&dir);
}

/// A title's preparation worker (`XCL_PRECOMPILE_PARENT`) leaves the whole form of a split
/// program in the driver cache besides its pieces: the title needs it at a split program's first
/// ExecuteIndirect, and builds it there itself when it is missing.
/// A startup worker keeps one ABI whole for a split program. A fresh runtime process can load
/// and dispatch it without preparing the pieces.
#[test]
fn a_preparation_worker_also_builds_a_split_programs_whole_form() {
fn a_preparation_worker_keeps_a_split_programs_abi_whole() {
use std::{fs, process::Command};
use std::collections::BTreeSet;
use xcl::gpu::recomp::pso::{console_to_dxil_in, Stage};
const TEST: &str = "a_preparation_worker_keeps_a_split_programs_abi_whole";
const SPLIT_LIMIT: &str = "16";
let blob = console_cs(&guarded_adds(), 2 << 1 | 1 << 7, [32, 1, 1]);
// Translate with the worker's split settings in a separate process, so other tests
// do not inherit them. Derive the expected artifacts independently of the build loop.
if let Some(driver) = std::env::var_os("XCL_TEST_SPLIT_DRIVER_FILES") {
let windows = std::env::var("XCL_TEST_SPLIT_DRIVER_WINDOWS").unwrap().parse().unwrap();
let split_wave64 = std::env::var("XCL_TEST_SPLIT_DRIVER_WAVE64").unwrap() == "1";
let c = console_to_dxil_in(&blob, Stage::Compute, 0, split_wave64, windows).unwrap();
assert!(c.samplers.is_empty());
let chain = c.dispatch_chain.unwrap();
assert!(chain.pieces.len() >= 2);
let expected = format!("{:016x}-{:x}-0.pso", xcl::gpu::shader::fnv64(&c.dxil), c.dxil.len());
let actual: BTreeSet<_> = fs::read_dir(driver).unwrap().map(|entry| {
let entry = entry.unwrap();
assert!(entry.file_type().unwrap().is_file() && entry.metadata().unwrap().len() > 0);
entry.file_name().into_string().unwrap()
}).collect();
assert_eq!(actual, BTreeSet::from([expected]));
return;
}
let _serial = SERIAL.lock().unwrap_or_else(|e| e.into_inner());
if xcl::gpu::recomp::dxc::location().is_err() {
runner::skip_test("no DXC");
Expand All @@ -323,39 +345,59 @@ fn a_preparation_worker_also_builds_a_split_programs_whole_form() {
runner::skip_test("no wave32 GPU");
return;
}
if xcl::hle::d3d12x::backend() != xcl::hle::d3d12x::Backend::Real {
return runner::skip_test("no real D3D12 device");
}
let windows = xcl::gpu::recomp::pso::mem_windows();
let worker_windows = windows & !(xcl::gpu::recomp::HEAP_WINDOWS | xcl::gpu::recomp::HEAP_FLAT);
let split_wave64 = if runner::wave64_supported() == Ok(true) { "0" } else { "1" };
let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let dir = std::env::temp_dir().join(format!("xcl-worker-whole-{}-{nonce}", std::process::id()));
let input = dir.join("input");
let cache = dir.join("cache");
fs::create_dir_all(&input).unwrap();
fs::write(input.join("split.bin"), console_cs(&split_program(), 2 << 1 | 1 << 7, [32, 1, 1])).unwrap();
let out = Command::new(env!("CARGO_BIN_EXE_xcl"))
.arg("shaders")
.arg(&input)
.args(["--precompile", "--pipelines", "--windows", "1"])
.env("XCL_DXIL_CACHE", &cache)
.env("XCL_DIRECT_DXIL", "1")
.env("XCL_DIRECT_SPLIT_INSTRUCTIONS", "12")
.env("XCL_PSO_DISK_CACHE", "1")
// as `pipelines_in_workers` starts it: this test is its parent
.env("XCL_PRECOMPILE_PARENT", std::process::id().to_string())
.output()
.unwrap();
let text = String::from_utf8_lossy(&out.stdout).into_owned();
assert!(out.status.success(), "{text}
{}", String::from_utf8_lossy(&out.stderr));
let files: Vec<_> = fs::read_dir(cache.join("driver")).unwrap().flatten().map(|e| e.path()).collect();
let is_piece = |p: &std::path::Path| {
p.extension().is_some_and(|e| e == "pso") && p.file_name().is_some_and(|n| n.to_string_lossy().ends_with(".chain.pso"))
fs::write(input.join("split.bin"), blob).unwrap();
let run_worker = || {
let out = Command::new(env!("CARGO_BIN_EXE_xcl"))
.arg("shaders")
.arg(&input)
.args(["--precompile", "--pipelines", "--windows", &worker_windows.to_string()])
.env("XCL_DXIL_CACHE", &cache)
.env("XCL_DIRECT_DXIL", "1")
.env("XCL_DIRECT_SPLIT_INSTRUCTIONS", SPLIT_LIMIT)
.env("XCL_PSO_DISK_CACHE", "1")
.env("XCL_PIPELINE_MAX_KB", "0")
.env("XCL_PRECOMPILE_PARENT", std::process::id().to_string())
.output().unwrap();
let text = String::from_utf8_lossy(&out.stdout).into_owned();
assert!(out.status.success(), "{text}\n{}", String::from_utf8_lossy(&out.stderr));
text
};
let pieces = files.iter().filter(|p| is_piece(p)).count();
let whole = files.iter().filter(|p| p.extension().is_some_and(|e| e == "pso") && !is_piece(p)).count();
assert!(pieces >= 2, "a blob for each split piece: {files:?}\n{text}");
assert_eq!(whole, 1, "one blob for the whole form: {files:?}\n{text}");
assert!(text.contains(&format!("pipelines made on the GPU {}, refused 0", pieces + whole)), "the whole form was not built: {text}");
assert_eq!(files.len(), pieces + whole, "only a blob for each piece and the whole form: {files:?}
{text}");
assert!(files.iter().all(|p| p.metadata().unwrap().len() > 0));
let cold = run_worker();
assert!(cold.contains("pipelines made on the GPU 1, refused 0"), "{cold}");
assert!(cold.contains("pipelines loaded from the driver cache 0"), "{cold}");
let driver = cache.join("driver");
let child = |filter: &str, variable: &str, value: &std::ffi::OsStr, child_cache: &std::path::Path| {
let check = Command::new(std::env::current_exe().unwrap())
.args(["--exact", filter, "--nocapture"])
.env(variable, value)
.env("XCL_TEST_SPLIT_DRIVER_WINDOWS", windows.to_string())
.env("XCL_TEST_SPLIT_DRIVER_WAVE64", split_wave64)
.env("XCL_DXIL_CACHE", child_cache)
.env("XCL_DIRECT_DXIL", "1")
.env("XCL_DIRECT_SPLIT_INSTRUCTIONS", SPLIT_LIMIT)
.env("XCL_PSO_DISK_CACHE", "1")
.output().unwrap();
assert!(check.status.success() && String::from_utf8_lossy(&check.stdout).contains("1 passed"),
"{}\n{}", String::from_utf8_lossy(&check.stdout), String::from_utf8_lossy(&check.stderr));
};
child(TEST, "XCL_TEST_SPLIT_DRIVER_FILES", driver.as_os_str(), &dir.join("expected"));
let warm = run_worker();
assert!(warm.contains("previously verified native compute pipelines 1")
|| warm.contains("pipelines loaded from the driver cache 1"), "{warm}");
assert!(warm.contains("fresh GPU pipeline creations 0"), "{warm}");
child(TEST, "XCL_TEST_SPLIT_DRIVER_FILES", driver.as_os_str(), &dir.join("expected"));
child("split_compute_prefers_the_offline_whole_pipeline", "XCL_TEST_WHOLE_CASE", std::ffi::OsStr::new("hit"), &cache);
let _ = fs::remove_dir_all(&dir);
}

Expand Down
Loading