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: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,9 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder
<details>
<summary><b>Switches, caches, logs and the files XCL writes</b></summary>

- 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`
Expand Down
21 changes: 17 additions & 4 deletions crates/xcl/src/gpu/dxil/compact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Plan> {
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::<usize>() >= 20_000
}
Expand Down
15 changes: 13 additions & 2 deletions crates/xcl/src/gpu/dxil/compact_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u8> {
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();
Expand Down Expand Up @@ -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();
Expand Down
10 changes: 7 additions & 3 deletions crates/xcl/src/gpu/dxil/kernel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<bool> {
match std::env::var("XCL_DIRECT_COMPACT").as_deref() {
Ok("1") => Some(true),
Expand Down Expand Up @@ -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());
}
Expand Down
1 change: 1 addition & 0 deletions crates/xcl/src/gpu/dxil/module/opt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
73 changes: 73 additions & 0 deletions crates/xcl/src/gpu/dxil/module/split.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<Option<Vec<_>>>()?;
Some(DispatchChain { pieces, dwords_per_group: stride.checked_mul(threads[0])? })
Expand Down Expand Up @@ -313,6 +316,38 @@ fn inst(v: Value) -> Option<usize> {
}

impl Module {
fn reuse_piece_slots(&self, plan: &Plan, slots: &BTreeMap<Value, u32>) -> Option<(u32, BTreeMap<Value, u32>)> {
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<usize> {
match v {
Value::Global(g) => Some(g as usize),
Expand Down Expand Up @@ -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();
Expand Down
3 changes: 3 additions & 0 deletions crates/xcl/src/gpu/recomp/pso.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading
Loading