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
138 changes: 122 additions & 16 deletions crates/xcl/src/gpu/dxil/compact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,8 +129,70 @@ fn slot(lw: &mut Lw, var: u32) -> Value {
init.slot(s, var)
}

/// Default class threshold and inner group size for `Nest::Auto`.
pub const AUTO_NEST_MIN_CLASSES: usize = 512;
pub const AUTO_NEST_GROUP_SIZE: usize = 32;

/// Dispatch nesting policy for the direct DXIL compact form (`XCL_DIRECT_COMPACT_NEST`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Nest {
/// Single flat `switch(class)` with one shared loop latch.
Flat,
/// Two-level nested switch (groups of [`AUTO_NEST_GROUP_SIZE`]) once class count reaches
/// [`AUTO_NEST_MIN_CLASSES`], flat below that.
Auto,
/// Two-level nested switch with explicit power-of-two inner group size whenever `classes > p`.
Fixed(usize),
}

impl Nest {
/// Resolves the inner group size for a program with `classes` distinct block classes,
/// returning `None` for flat dispatch.
pub fn group_size(self, classes: usize) -> Option<usize> {
match self {
Nest::Flat => None,
Nest::Auto => (classes >= AUTO_NEST_MIN_CLASSES).then_some(AUTO_NEST_GROUP_SIZE),
Nest::Fixed(p) => (p >= 2 && p.is_power_of_two() && classes > p).then_some(p),
}
}

/// Non-default cache tag folded into the direct-DXIL translated cache identity.
pub fn cache_tag(self) -> Option<String> {
match self {
Nest::Auto => None,
Nest::Flat => Some("xcl-direct-compact-nest-0".into()),
Nest::Fixed(p) => Some(format!("xcl-direct-compact-nest-{p}")),
}
}
}

/// `XCL_DIRECT_COMPACT_NEST`: `auto` or unset nests `>= 512` classes into groups of 32;
/// `0` / `off` keeps a flat switch; a power of two in `2..=65536` fixes the inner group size.
pub fn nest_mode() -> Nest {
parse_nest(std::env::var("XCL_DIRECT_COMPACT_NEST").ok().as_deref())
}

pub(crate) fn parse_nest(val: Option<&str>) -> Nest {
let Some(raw) = val.map(str::trim) else { return Nest::Auto };
if raw.is_empty() || raw.eq_ignore_ascii_case("auto") {
return Nest::Auto;
}
if raw == "0" || raw.eq_ignore_ascii_case("off") {
return Nest::Flat;
}
match raw.parse::<usize>() {
Ok(p) if (2..=65536).contains(&p) && p.is_power_of_two() => Nest::Fixed(p),
_ => Nest::Auto,
}
}

/// Lowers the program as one loop from `head` to `exit` that switches to each block's class.
pub fn emit(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block) -> LResult<()> {
emit_with_nest(lw, cfg, p, head, exit, nest_mode())
}

/// Like [`emit`], with an explicit [`Nest`] policy.
pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block, nest: Nest) -> LResult<()> {
let n = p.order.len();
let (cb, pb) = p.widths();
let width = cb + pb;
Expand Down Expand Up @@ -173,9 +235,34 @@ pub fn emit(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block) -> LResu
let (taken, not_taken) = (lw.add(b, step_t), lw.add(b, step_f));
let cases: Vec<Block> = p.rep.iter().map(|_| lw.block(Some(0))).collect();
let latch = lw.block(Some(0));
let arms: Vec<(Value, Block)> = cases.iter().enumerate().skip(1).map(|(k, &c)| (lw.c(k as u32), c)).collect();
lw.s.m.switch(class, cases[0], &arms);
for (&c, &r) in cases.iter().zip(&p.rep) {
let group_size = nest.group_size(p.rep.len());
let group_latches: Vec<Block> = if let Some(gs) = group_size {
let groups = p.rep.len().div_ceil(gs);
let shift = gs.trailing_zeros();
let entries: Vec<Block> = (0..groups).map(|_| lw.block(Some(0))).collect();
let latches: Vec<Block> = (0..groups).map(|_| lw.block(Some(0))).collect();
let grp = lw.lshrc(class, shift);
let outer_arms: Vec<(Value, Block)> = entries.iter().enumerate().skip(1).map(|(g, &blk)| (lw.c(g as u32), blk)).collect();
lw.s.m.switch(grp, entries[0], &outer_arms);
for (g, &entry_blk) in entries.iter().enumerate() {
let lo = g * gs;
let hi = (lo + gs).min(p.rep.len());
lw.s.m.set_block(entry_blk);
if hi - lo == 1 {
lw.s.m.br(cases[lo]);
} else {
let inner_arms: Vec<(Value, Block)> = (lo + 1..hi).map(|k| (lw.c(k as u32), cases[k])).collect();
lw.s.m.switch(class, cases[lo], &inner_arms);
}
}
latches
} else {
let arms: Vec<(Value, Block)> = cases.iter().enumerate().skip(1).map(|(k, &c)| (lw.c(k as u32), c)).collect();
lw.s.m.switch(class, cases[0], &arms);
Vec::new()
};
for (k, (&c, &r)) in cases.iter().zip(&p.rep).enumerate() {
let target_latch = group_size.map_or(latch, |gs| group_latches[k / gs]);
lw.s.m.set_block(c);
lw.init.mem = Some(c);
lw.ssa.begin_log();
Expand All @@ -189,7 +276,7 @@ pub fn emit(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block) -> LResu
lw.s.m.set_block(out);
let end = lw.c(END);
lw.s.m.store(to, end, 4);
lw.s.m.br(latch);
lw.s.m.br(target_latch);
lw.s.m.set_block(body);
let one = lw.c(1);
let l = lw.sub(left, one);
Expand All @@ -211,18 +298,37 @@ pub fn emit(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block) -> LResu
lw.s.m.store(p, v, 4);
}
lw.s.m.store(to, next, 4);
lw.s.m.br(latch);
lw.s.m.br(target_latch);
}
if group_size.is_some() {
// Each group latch performs the loop-exit check rather than forwarding with an empty
// unconditional branch, so driver CFG simplification preserves the two-level merge fan-in
// during SSA promotion without adding extra runtime instructions.
for &gl in &group_latches {
lw.s.m.set_block(gl);
let nxt = lw.s.m.load(to, 4);
let stop = lw.cmpc(Pred::UGe, nxt, n as u32);
lw.s.m.cond_br(stop, exit, latch);
}
// the epilogue's reads load in exit
lw.init.mem = Some(exit);
lw.s.m.set_block(latch);
let next = lw.s.m.load(to, 4);
lw.s.m.store(at, next, 4);
lw.br(head);
lw.seal(head);
} else {
// the epilogue's reads load here
lw.init.mem = Some(latch);
lw.s.m.set_block(latch);
let next = lw.s.m.load(to, 4);
let stop = lw.cmpc(Pred::UGe, next, n as u32);
let cont = lw.block(Some(1));
lw.cond_br(stop, exit, cont);
lw.s.m.set_block(cont);
lw.s.m.store(at, next, 4);
lw.br(head);
lw.seal(head);
}
// the epilogue's reads load here
lw.init.mem = Some(latch);
lw.s.m.set_block(latch);
let next = lw.s.m.load(to, 4);
let stop = lw.cmpc(Pred::UGe, next, n as u32);
let cont = lw.block(Some(1));
lw.cond_br(stop, exit, cont);
lw.s.m.set_block(cont);
lw.s.m.store(at, next, 4);
lw.br(head);
lw.seal(head);
Ok(())
}
181 changes: 181 additions & 0 deletions crates/xcl/src/gpu/dxil/compact_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,3 +124,184 @@ fn a_mask_read_whole_after_one_copy_only_splits_the_class() {
assert_eq!(p.order.len(), 4);
assert_ne!(p.class[0], p.class[2]);
}

/// Builds a straight-line + loop program with `extra_classes` distinct blocks (each adding a
/// distinct immediate to `s0` / `v1`, separated by a trivial conditional branch so every block
/// becomes its own compact class), plus a bounded loop at the end.
fn multi_class_program(extra_classes: usize, loop_iters: u32) -> Vec<u8> {
let i = |n: &str, e: &str, f: &[(&str, u64)], lit: Option<u32>| {
encode(n, e, f, lit).unwrap_or_else(|x| panic!("{n}: {x}"))
};
let mut v = Vec::new();
for k in 0..extra_classes {
let lit = (k as u32 + 1) * 7 + 3;
v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 255)], Some(lit)));
v.extend(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 0), ("VSRC1", 1)], None));
v.extend(i("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 128)], None));
v.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0)], None));
}
// Loop header block (distinct class) that counts `s4` up to `loop_iters`
v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 4), ("SSRC0", 4), ("SSRC1", 129)], None));
v.extend(i("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 4), ("SSRC1", 255)], Some(loop_iters)));
v.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFC)], None));
v.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 129)], None));
v.extend(i("S_ENDPGM", "ENC_SOPP", &[], None));
v
}

#[test]
fn parse_nest_and_group_size_policy() {
use super::compact::{parse_nest, Nest, AUTO_NEST_GROUP_SIZE, AUTO_NEST_MIN_CLASSES};

assert_eq!(parse_nest(None), Nest::Auto);
assert_eq!(parse_nest(Some("")), Nest::Auto);
assert_eq!(parse_nest(Some("auto")), Nest::Auto);
assert_eq!(parse_nest(Some("AUTO")), Nest::Auto);
assert_eq!(parse_nest(Some("0")), Nest::Flat);
assert_eq!(parse_nest(Some("off")), Nest::Flat);
assert_eq!(parse_nest(Some("OFF")), Nest::Flat);
assert_eq!(parse_nest(Some("2")), Nest::Fixed(2));
assert_eq!(parse_nest(Some("16")), Nest::Fixed(16));
assert_eq!(parse_nest(Some("32")), Nest::Fixed(32));
assert_eq!(parse_nest(Some("65536")), Nest::Fixed(65536));
// Invalid values fall back to Auto
for bad in ["1", "3", "30", "131072", "-4", "bogus"] {
assert_eq!(parse_nest(Some(bad)), Nest::Auto, "bad={bad}");
}

assert_eq!(Nest::Flat.group_size(1024), None);
assert_eq!(Nest::Auto.group_size(AUTO_NEST_MIN_CLASSES - 1), None);
assert_eq!(Nest::Auto.group_size(AUTO_NEST_MIN_CLASSES), Some(AUTO_NEST_GROUP_SIZE));
assert_eq!(Nest::Fixed(4).group_size(4), None);
assert_eq!(Nest::Fixed(4).group_size(5), Some(4));

assert_eq!(Nest::Auto.cache_tag(), None);
assert_eq!(Nest::Flat.cache_tag().as_deref(), Some("xcl-direct-compact-nest-0"));
assert_eq!(Nest::Fixed(16).cache_tag().as_deref(), Some("xcl-direct-compact-nest-16"));
}

#[test]
fn nested_compact_ir_structure_bounds_switch_fanout_and_merge_fanin() {
use super::compact::{emit_with_nest, plan, Nest};
use super::module::{Block, InstInfo};

// 11 extra classes + loop header + exit block = 13 classes -> with group size 4:
// 4 groups of sizes (4, 4, 4, 1), exercising full inner switches and a singleton tail group.
let code = multi_class_program(11, 3);
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 o = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 };

let inspect = |nest: Nest| -> (usize, usize, usize, usize) {
let mut lw = super::lower::Lw::new(&cfg.insts, &leaders, o, &super::kernel::Entry::Kernel);
lw.setup_lanes();
let lane = lw.lane;
let k = lw.c((crate::gpu::recomp::KERNEL_VGPRS * 4) as u32);
let b = lw.mul(lane, k);
lw.init.vgpr_base = Some(lw.addc(b, (crate::gpu::recomp::KERNEL_SGPRS * 4) as u32));
let p = plan(&cfg, &lw).unwrap();
assert_eq!(p.rep.len(), 13);
let h0 = lw.block(None);
let exit = lw.block(None);
lw.edge(Block(0), h0);
emit_with_nest(&mut lw, &cfg, &p, h0, exit, nest).unwrap();
let m = &lw.s.m;
let mut switches = 0usize;
let mut max_switch_targets = 0usize;
let mut preds = vec![0usize; m.block_count()];
for b in 0..m.block_count() {
if let Some(&last) = m.block_insts(Block(b as u32)).last() {
if let InstInfo::Term(cond, succs) = m.inst_info(last) {
if cond.is_some() && succs.len() > 2 {
switches += 1;
max_switch_targets = max_switch_targets.max(succs.len());
}
for s in succs {
preds[s.0 as usize] += 1;
}
}
}
}
let max_preds = preds.into_iter().max().unwrap_or(0);
(p.rep.len(), switches, max_switch_targets, max_preds)
};

let (classes, flat_sw, flat_max_sw, flat_max_preds) = inspect(Nest::Flat);
assert_eq!(flat_sw, 1);
assert_eq!(flat_max_sw, classes);
assert!(flat_max_preds >= classes, "flat latch should merge all {classes} classes, got {flat_max_preds}");

// Group size 4 on 13 classes: 1 outer switch (4 groups) + 3 inner switches (4th group is singleton Br) = 4 switches
let (_, n4_sw, n4_max_sw, n4_max_preds) = inspect(Nest::Fixed(4));
assert_eq!(n4_sw, 4);
assert_eq!(n4_max_sw, 4);
assert!(n4_max_preds <= 5, "nested group-4 max block fan-in should be <= 5, got {n4_max_preds}");

// Group size 8 on 13 classes: 1 outer switch (2 groups: 8 and 5) -> outer switch has 2 targets (still Op::Switch),
// inner switches have 8 and 5 targets; max block fan-in bounded by group size + 1 (loop header early exit).
let (_, _, n8_max_sw, n8_max_preds) = inspect(Nest::Fixed(8));
assert_eq!(n8_max_sw, 8);
assert!(n8_max_preds <= 9, "nested group-8 max block fan-in should be <= 9, got {n8_max_preds}");
}

#[test]
fn gpu_nested_compact_matches_plain_and_flat() {
use super::compact::Nest;
use super::kernel::translate_full_nested;

match (runner::adapter(), runner::wave64_programs_supported(), crate::gpu::recomp::dxc::location()) {
(Ok(_), Ok(true), Ok(_)) => {}
(a, _, d) => return runner::skip_test(if a.is_err() { "no GPU" } else if d.is_err() { "no DXC" } else { "no wave64" }),
}
let o = KernelOptions { wave64: true, split: runner::split_wave64(), mem_windows: 1, sampler_base: 0 };

// 1. Repeated-block program (11 classes): exercise Flat, Fixed(2) (singleton tail), Fixed(4), Fixed(8)
let mut st = KernelState::default();
(st.sgpr[1], st.sgpr[2]) = (3, 12);
for lane in 0..KERNEL_LANES {
st.vgpr[lane][0] = lane as u32;
}
let code = repeated(40);
let plain = {
let k = translate_full_as(&code, o, false).expect("plain");
runner::run_with_statics(&k.dxil, &st, &[], &[], &[], &k.static_samplers).expect("plain GPU run")
};
for nest in [Nest::Flat, Nest::Fixed(2), Nest::Fixed(4), Nest::Fixed(8)] {
let k = translate_full_nested(&code, o, nest).unwrap_or_else(|e| panic!("nest {nest:?}: {e}"));
let got = runner::run_with_statics(&k.dxil, &st, &[], &[], &[], &k.static_samplers)
.unwrap_or_else(|e| panic!("GPU run {nest:?}: {e}"));
assert_eq!((&got.sgpr, &got.vgpr, got.scc), (&plain.sgpr, &plain.vgpr, plain.scc), "repeated {nest:?}");
}

// 2. Multi-class program (17 classes: 4*4 + 1 singleton tail) with normal loop termination
let mut st2 = KernelState::default();
for lane in 0..KERNEL_LANES {
st2.vgpr[lane][1] = lane as u32;
}
let mc = multi_class_program(15, 5);
let plain2 = {
let k = translate_full_as(&mc, o, false).expect("plain multi-class");
runner::run_with_statics(&k.dxil, &st2, &[], &[], &[], &k.static_samplers).expect("plain multi-class GPU run")
};
assert_eq!(plain2.sgpr[4], 5);
assert_eq!(plain2.sgpr[5], 1);
for nest in [Nest::Flat, Nest::Fixed(4), Nest::Fixed(8)] {
let k = translate_full_nested(&mc, o, nest).unwrap_or_else(|e| panic!("mc nest {nest:?}: {e}"));
let got = runner::run_with_statics(&k.dxil, &st2, &[], &[], &[], &k.static_samplers)
.unwrap_or_else(|e| panic!("mc GPU run {nest:?}: {e}"));
assert_eq!((&got.sgpr, &got.vgpr, got.scc), (&plain2.sgpr, &plain2.vgpr, plain2.scc), "multi-class {nest:?}");
}

// 3. Nested loop-budget exhaustion: budget hits 0 inside a nested group and exits through group_latch -> exit
let mc_budget = multi_class_program(9, super::lower::LOOP_BUDGET + 1);
let plain3 = {
let k = translate_full_as(&mc_budget, o, false).expect("plain budget");
runner::run_with_statics(&k.dxil, &KernelState::default(), &[], &[], &[], &k.static_samplers)
.expect("plain budget GPU run")
};
assert_eq!((plain3.sgpr[4], plain3.sgpr[5]), (super::lower::LOOP_BUDGET, 0));
let k_n4 = translate_full_nested(&mc_budget, o, Nest::Fixed(4)).expect("nested budget");
let got3 = runner::run_with_statics(&k_n4.dxil, &KernelState::default(), &[], &[], &[], &k_n4.static_samplers)
.expect("nested budget GPU run");
assert_eq!((got3.sgpr, got3.vgpr, got3.scc), (plain3.sgpr, plain3.vgpr, plain3.scc), "nested loop budget");
}
Loading
Loading