diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 82cf4c0905..eed745559e 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -225,7 +225,7 @@ fn translate_on_this_thread( } Entry::Compute(cs) => { let (tid, gtid) = lw.setup_lanes_compute(cs.threads, uses_lds); - if split && !uses_lds && cs.threads == [64, 1, 1] { split_tid = Some(tid); } + if split && !uses_lds && cs.threads.iter().product::() % 64 == 0 { split_tid = Some(tid); } compute_init(&mut lw, cs, tid, gtid); cs.threads } diff --git a/crates/xcl/src/gpu/dxil/lanes.rs b/crates/xcl/src/gpu/dxil/lanes.rs index 4ee59b5cc8..854a09adf4 100644 --- a/crates/xcl/src/gpu/dxil/lanes.rs +++ b/crates/xcl/src/gpu/dxil/lanes.rs @@ -300,6 +300,7 @@ impl Lw { let alive = self.cmpc(Pred::Eq, dead, 0); let has = self.cmpc(Pred::Ne, xn, 0); let go = self.land(alive, has); + let region = (self.cur(), self.s.m.block_count()); let _ = self.guarded(go, &mut |lw| { lw.s.barrier(barrier::TGSM_FENCE); let t = lw.s.m.i1c(true); @@ -354,6 +355,7 @@ impl Lw { }); let one = self.c(1); let ho = self.xor(h, one); + self.s.m.finish_spin_region(region.0, region.1); let theirs = at(self, ho); let metv = self.rd(met); let ok = self.nz(metv); diff --git a/crates/xcl/src/gpu/dxil/module.rs b/crates/xcl/src/gpu/dxil/module.rs index d72ef6fc38..bb84cfc599 100644 --- a/crates/xcl/src/gpu/dxil/module.rs +++ b/crates/xcl/src/gpu/dxil/module.rs @@ -254,6 +254,7 @@ pub struct Module { insts: Vec, def_block: Vec, blocks: Vec>, + spin_regions: Vec>, cur: Block, insert_before_term: bool, md: Vec, @@ -282,6 +283,7 @@ impl Module { insts: Vec::new(), def_block: Vec::new(), blocks: vec![Vec::new()], + spin_regions: Vec::new(), cur: Block(0), insert_before_term: false, md: Vec::new(), @@ -519,6 +521,14 @@ impl Module { self.blocks.push(Vec::new()); Block(self.blocks.len() as u32 - 1) } + /// Keep both halves' signal and wait in the same dispatch. The join can + /// begin the next piece since the exchange slots are checkpointed. + pub(super) fn finish_spin_region(&mut self, start: Block, first_new: usize) { + let mut region = vec![start]; + region.extend((first_new..self.blocks.len()).map(|i| Block(i as u32)).filter(|&b| b != self.cur)); + self.spin_regions.push(region); + } + pub fn entry_block(&self) -> Block { Block(0) } diff --git a/crates/xcl/src/gpu/dxil/module/split.rs b/crates/xcl/src/gpu/dxil/module/split.rs index 7a88b9ae11..e4d2bdfb12 100644 --- a/crates/xcl/src/gpu/dxil/module/split.rs +++ b/crates/xcl/src/gpu/dxil/module/split.rs @@ -1,6 +1,7 @@ //! Partition the optimized compute entry at CFG edges. A dispatch cannot //! jump back to an earlier dispatch, so a strongly connected component is -//! indivisible. Each crossing edge has its own compact state layout. +//! indivisible. Every carried value keeps its payload slots for the whole +//! chain; split wave64 groups add one region for their exchange state. use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; @@ -80,6 +81,45 @@ impl Scratch { Self { uav, base: s.m.bin(BinOp::Mul, index, four), bytes_per_slot: threads * 4 } } + /// Every logical thread participates, including threads whose guest path + /// skipped this piece. Exactly one thread owns each shared word. + fn transfer_shared(&self, s: &mut Shader, lane: Value, lanes: u32, arrays: &[(Value, u32, u32)], restore: bool) { + use crate::gpu::dxil::ops::barrier::GROUP_SYNC; + if !restore { s.barrier(GROUP_SYNC); } + for &(global, count, slot) in arrays { + for page in 0..count.div_ceil(lanes) { + let remaining = count - page * lanes; + let mut join = None; + if remaining < lanes { + let n = s.m.i32c(remaining); + let active = s.m.cmp(super::Pred::ULt, lane, n); + let body = s.m.new_block(); + let next = s.m.new_block(); + s.m.cond_br(active, body, next); + s.m.set_block(body); + join = Some(next); + } + let zero = s.m.i32c(0); + let base = s.m.i32c(page * lanes); + let index = s.m.bin(BinOp::Add, base, lane); + let ptr = s.m.gep(global, &[zero, index]); + let addr = self.at(&mut s.m, slot + page); + if restore { + let v = s.raw_load(self.uav, addr, 1)[0]; + s.m.store(ptr, v, 4); + } else { + let v = s.m.load(ptr, 4); + s.raw_store(self.uav, addr, &[v]); + } + if let Some(next) = join { + s.m.br(next); + s.m.set_block(next); + } + } + } + if restore { s.barrier(GROUP_SYNC); } + } + fn at(&self, m: &mut Module, slot: u32) -> Value { let offset = m.i32c(slot * self.bytes_per_slot); m.bin(BinOp::Add, self.base, offset) @@ -87,11 +127,16 @@ impl Scratch { } impl Shader { - /// Start with full native wave32 groups. A fresh dispatch can assign a - /// different physical wave to a group; wave-lane index identifies the - /// continuation within a full, single-wave group. + /// Native wave32 uses the hardware lane in a single full wave. Split + /// wave64 recreates the flat console thread ID on every dispatch, including + /// when the hardware schedules the waves in a different order. pub(crate) fn split_compute(&self, threads: [u32; 3], split_tid: Option, limit: usize) -> Option { - if self.m.globals.iter().any(|g| !g.constant && !(split_tid.is_some() && matches!(g.name.as_str(), "xcl_xw" | "xcl_xs"))) { + let lanes: u32 = threads.into_iter().try_fold(1u32, u32::checked_mul)?; + let multi = split_tid.is_some() && lanes > 64; + if self.m.globals.iter().any(|g| !g.constant + && !(split_tid.is_some() && matches!(g.name.as_str(), "xcl_xw" | "xcl_xs")) + && !(multi && g.name == "xcl_xc")) + { return None; } if self.m.blocks.iter().map(Vec::len).sum::() <= limit { return None; } @@ -104,6 +149,8 @@ impl Shader { for &i in self.m.blocks.iter().flatten() { self.m.insts[i as usize].op.for_each_operand(|v| { consumed.insert(v); }); } + let root_is = |v, name| self.m.global_root(v).is_some_and(|g| self.m.globals[g].name == name); + let spins: HashSet<_> = self.m.spin_regions.iter().flatten().copied().collect(); for (b, block) in self.m.blocks.iter().enumerate() { // In a single split console wave each inter-half exchange begins // with TGSM stores, one rendezvous, peer loads and a rendezvous. @@ -112,10 +159,15 @@ impl Shader { for &i in block { if b == 0 && prefix.contains(&i) { continue; } match &self.m.insts[i as usize].op { + Op::AtomicRmw(super::RmwOp::Add, p, _) if multi && root_is(*p, "xcl_xc") => {} + Op::Load(p, _) | Op::Store(p, _, _) if multi && root_is(*p, "xcl_xs") => {} + Op::Call(f, args) if multi && spins.contains(&Block(b as u32)) + && self.m.funcs[*f as usize].name == "dx.op.barrier" + && self.m.const_u64(args[1]) == Some(crate::gpu::dxil::ops::barrier::TGSM_FENCE as u64) => {} Op::Alloca(..) | Op::AtomicRmw(..) | Op::CmpXchg(..) => return None, - Op::Store(..) if split_tid.is_some() && exchange <= 1 => exchange = 1, + Op::Store(..) if split_tid.is_some() && !multi && exchange <= 1 => exchange = 1, Op::Load(p, _) if self.m.global_root(*p).is_some_and(|g| self.m.globals[g].constant) => {} - Op::Load(..) if split_tid.is_some() && matches!(exchange, 2 | 3) => exchange = 3, + Op::Load(..) if split_tid.is_some() && !multi && matches!(exchange, 2 | 3) => exchange = 3, Op::Load(..) | Op::Store(..) => return None, Op::Call(f, args) if self.m.funcs[*f as usize].name == "dx.op.barrier" && self.m.const_u64(args[1]) == Some(crate::gpu::dxil::ops::barrier::GROUP_SYNC as u64) => { @@ -148,12 +200,20 @@ impl Shader { 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::>>()?; - Some(DispatchChain { pieces, dwords_per_group: stride.checked_mul(threads[0])? }) + let mut shared = Vec::new(); + if multi { + for (i, g) in self.m.globals.iter().enumerate().filter(|(_, g)| matches!(g.name.as_str(), "xcl_xc" | "xcl_xs")) { + let TypeDef::Array(n, _) = self.m.types[g.ty.0 as usize] else { return None }; + shared.push((Value::Global(i as u32), u32::try_from(n).ok()?, stride)); + stride = stride.checked_add(u32::try_from(n).ok()?.div_ceil(lanes))?; + } + } + stride.checked_mul(lanes)?.checked_mul(4)?; + let pieces = (0..plan.blocks.len()).map(|i| self.make_piece(&plan, i, stride, &slots, threads, &prefix, &shared)).collect::>>()?; + Some(DispatchChain { pieces, dwords_per_group: stride.checked_mul(lanes)? }) } - fn make_piece(&self, plan: &Plan, stage: usize, stride: u32, slots: &BTreeMap, threads: [u32; 3], prefix: &[u32]) -> Option> { + fn make_piece(&self, plan: &Plan, stage: usize, stride: u32, slots: &BTreeMap, threads: [u32; 3], prefix: &[u32], shared: &[(Value, u32, u32)]) -> Option> { let src = &self.m; let mut dst = self.dispatch_piece(); let mut values = HashMap::new(); @@ -166,7 +226,12 @@ impl Shader { values.insert(Value::Inst(id), slab.group_id(src, &def.op, &mut dst.m, v)); } let lane = prefix.last().map(|&i| values[&Value::Inst(i)]).unwrap_or_else(|| dst.wave_lane_index()); - let scratch = Scratch::new(&mut dst, &slab, stride, threads[0], lane); + let lanes = threads.iter().product(); + let scratch = Scratch::new(&mut dst, &slab, stride, lanes, lane); + if stage > 0 && !shared.is_empty() { + scratch.transfer_shared(&mut dst, lane, lanes, shared, true); + } + let dispatch_entry = dst.m.current_block(); let local: HashMap<_, _> = plan.blocks[stage].iter().map(|&b| (b, dst.m.new_block())).collect(); let mut hops = HashMap::new(); let mut exits = HashMap::new(); @@ -189,7 +254,7 @@ impl Shader { hops.insert((edge.from, edge.to), hop); } } - dst.m.set_block(Block(0)); + dst.m.set_block(dispatch_entry); if let Some(sel) = selector { for v in incoming { if values.contains_key(&v) { continue; } @@ -206,6 +271,8 @@ impl Shader { dst.m.br(local[&Block(0)]); } dst.m.set_block(done); + let checkpoint = !shared.is_empty() && stage + 1 < plan.blocks.len(); + if checkpoint { scratch.transfer_shared(&mut dst, lane, lanes, shared, false); } dst.m.ret(); // Assign all instruction identities before fixing operands. A loop's @@ -219,6 +286,7 @@ impl Shader { if matches!(old.op, Op::Ret) && stage + 1 < plan.blocks.len() { let zero = dst.m.i32c(0); dst.raw_store(scratch.uav, scratch.base, &[zero]); + if checkpoint { dst.m.br(done); continue; } } let v = dst.m.push(old.op.clone(), old.ty); values.insert(Value::Inst(i), slab.group_id(src, &old.op, &mut dst.m, v)); @@ -263,7 +331,7 @@ impl Shader { } } dst.raw_store(scratch.uav, scratch.base, &[tag]); - dst.m.ret(); + if checkpoint { dst.m.br(done); } else { dst.m.ret(); } } src.place_restores(&mut dst, &scratch, slots, &deferred)?; dst.m.sink_cheap_piece_ops(); @@ -486,7 +554,7 @@ impl Module { fn indexed(&self, v: Value) -> Option { let op = &self.insts[inst(v)?].op; if let Op::Gep(Value::Global(g), indices) = op { - if self.globals[*g as usize].name == "xcl_xs" && indices.len() == 2 && self.const_u64(indices[0]) == Some(0) { + if matches!(self.globals[*g as usize].name.as_str(), "xcl_xs" | "xcl_xc") && indices.len() == 2 && self.const_u64(indices[0]) == Some(0) { return Some(indices[1]); } } @@ -611,7 +679,7 @@ impl Module { let mut visited = vec![false; self.blocks.len()]; let mut blocks = vec![Vec::new()]; let mut stages = vec![usize::MAX; self.blocks.len()]; - let mut used = 0; + let mut components = Vec::new(); for &root in &order { if visited[root] { continue; @@ -630,6 +698,32 @@ impl Module { } } } + for &b in &component { + stages[b] = components.len(); + } + components.push((cost, component)); + } + // A wait polling the peer's counter cannot complete if the peer's + // signal was deferred to another dispatch. Pack these SCCs together. + let mut through: Vec = (0..components.len()).collect(); + for region in &self.spin_regions { + let mut span = region.iter().map(|b| stages[b.0 as usize]).filter(|&i| i != usize::MAX); + if let Some(i) = span.next() { + let (lo, hi) = span.fold((i, i), |(lo, hi), i| (lo.min(i), hi.max(i))); + through[lo] = through[lo].max(hi); + } + } + let mut i = 0; + let mut used = 0; + while i < components.len() { + let first = i; + let mut last = i; + let mut cost = 0; + while i <= last { + last = last.max(through[i]); + cost += components[i].0; + i += 1; + } // The target is soft for an indivisible component. A component // above it occupies a piece by itself; bound that exception so a // very large loop still selects the whole pipeline. @@ -641,8 +735,8 @@ impl Module { used = 0; } used += cost; - for b in component { - stages[b] = blocks.len() - 1; + for (_, component) in &components[first..i] { + for &b in component { stages[b] = blocks.len() - 1; } } } @@ -975,6 +1069,149 @@ mod tests { assert!(chain.pieces.len() >= 2); } + #[test] + fn dispatch_chain_four_wave64s_preserves_partner_epochs() { + if !runner::wave32_supported().unwrap_or(false) { + runner::skip_test("no wave32 GPU"); + return; + } + let geometry = [16, 16, 1]; + let cs = CsInterface { threads: geometry, ..Default::default() }; + let options = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; + let mut lw = Lw::new(&[], &Default::default(), options, &Entry::Compute(cs)); + let (tid, _) = lw.setup_lanes_compute(geometry, false); + let half = lw.lshrc(tid, 5); + let group = lw.s.group_id(0); + let group_base = lw.shlc(group, 8); + let index = lw.add(group_base, tid); + let addr = lw.shlc(index, 2); + let mem = lw.mems[0]; + let initial = lw.s.raw_load(mem, addr, 1)[0]; + let acc = lw.tmp_var(); + lw.wr(acc, initial); + let odd_wave = lw.andc(tid, 64); + let odd_wave = lw.nz(odd_wave); + // Only odd guest waves perform every exchange. A single common + // exchange count for all guest waves would corrupt their results. + for round in 1..=12 { + let mut exchange = |lw: &mut Lw| { + let payload = lw.addc(half, round); + let peer = lw.exchange(payload); + let old = lw.rd(acc); + let sum = lw.add(old, peer); + lw.wr(acc, sum); + Ok(()) + }; + if round % 2 == 1 { lw.guarded(odd_wave, &mut exchange).unwrap(); } + else { exchange(&mut lw).unwrap(); } + let next = lw.block(Some(1)); + lw.br(next); + lw.s.m.set_block(next); + } + let v = lw.rd(acc); + lw.s.raw_store(mem, addr, &[v]); + lw.s.m.ret(); + lw.s.m.optimize(); + let chain = lw.s.split_compute(geometry, Some(tid), 160).expect("split four guest waves"); + assert!(chain.pieces.len() >= 3); + let whole = lw.s.finish_optimized(geometry, Some(32)).unwrap(); + let input: Vec = (1..=512).collect(); + let expected: Vec<_> = input.iter().enumerate().map(|(i, v)| { + let tid = i as u32 % 256; + v + (1..=12).filter(|round| round % 2 == 0 || tid & 64 != 0) + .map(|round| ((tid / 32) ^ 1) + round).sum::() + }).collect(); + let groups = [2, 1, 1]; + let reference = runner::dispatch(&whole, groups, &[], &input).unwrap(); + assert_eq!(reference, expected); + assert_eq!(runner::dispatch_split(&chain, groups, &input).unwrap(), reference); + } + + /// Guest waves that returned still participate in the checkpoint rendezvous + /// while other waves keep advancing their partner counters and slot banks. + #[test] + fn dispatch_chain_exited_waves_preserve_other_waves_3d() { + if !runner::wave32_supported().unwrap_or(false) { + runner::skip_test("no wave32 GPU"); + return; + } + println!("CHAIN_EXIT_GPU={}", runner::adapter().unwrap()); + let geometry = [16, 16, 1]; + let cs = CsInterface { threads: geometry, ..Default::default() }; + let options = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; + let mut lw = Lw::new(&[], &Default::default(), options, &Entry::Compute(cs)); + let (tid, _) = lw.setup_lanes_compute(geometry, false); + let half = lw.lshrc(tid, 5); + let wave = lw.lshrc(tid, 6); + let [x, y, z] = [0, 1, 2].map(|axis| lw.s.group_id(axis)); + let z = lw.shlc(z, 1); + let row = lw.add(z, y); + let row = lw.shlc(row, 1); + let group = lw.add(row, x); + let base = lw.shlc(group, 8); + let index = lw.add(base, tid); + let addr = lw.shlc(index, 2); + let mem = lw.mems[0]; + let initial = lw.s.raw_load(mem, addr, 1)[0]; + let acc = lw.tmp_var(); + lw.wr(acc, initial); + let not_second_wave = lw.cmpc(Pred::Ne, wave, 1); + for round in 1..=12 { + if round == 1 || round == 7 { + let exit = lw.block(Some(1)); + let live = lw.block(Some(1)); + let stops = lw.cmpc(Pred::Eq, wave, if round == 1 { 0 } else { 2 }); + lw.cond_br(stops, exit, live); + lw.s.m.set_block(exit); + let old = lw.rd(acc); + let value = if round == 1 { lw.addc(old, 100_000) } else { old }; + lw.s.raw_store(mem, addr, &[value]); + lw.s.m.ret(); + lw.s.m.set_block(live); + } + let mut exchange = |lw: &mut Lw| { + let payload = lw.addc(half, round); + let peer = lw.exchange(payload); + let old = lw.rd(acc); + let value = lw.add(old, peer); + lw.wr(acc, value); + Ok(()) + }; + if round % 2 == 1 { lw.guarded(not_second_wave, &mut exchange).unwrap(); } + else { exchange(&mut lw).unwrap(); } + let next = lw.block(Some(1)); + lw.br(next); + lw.s.m.set_block(next); + } + let value = lw.rd(acc); + lw.s.raw_store(mem, addr, &[value]); + lw.s.m.ret(); + lw.s.m.optimize(); + let chain = lw.s.split_compute(geometry, Some(tid), 160).expect("split with exited guest waves"); + assert!(chain.pieces.len() >= 3); + let whole = lw.s.finish_optimized(geometry, Some(32)).unwrap(); + crate::gpu::dxil::validate::validate(&whole).expect("valid whole shader"); + let input: Vec<_> = (0..2064u32).map(|i| if i < 2048 { i + 17 } else { 0xdeadbeef }).collect(); + let expected: Vec<_> = input.iter().enumerate().map(|(i, &v)| { + if i >= 2048 { return v; } + let tid = i as u32 % 256; + let peer = (tid / 32) ^ 1; + match tid / 64 { + 0 => v + 100_000, + 1 => v + 6 * peer + 42, + 2 => v + 6 * peer + 21, + _ => v + 12 * peer + 78, + } + }).collect(); + println!("CHAIN_EXIT_STAGE whole pieces={} scratch_dwords_per_group={}", chain.pieces.len(), chain.dwords_per_group); + let reference = runner::dispatch(&whole, [2, 2, 2], &[], &input).unwrap(); + assert_eq!(reference, expected, "whole program CPU oracle"); + println!("CHAIN_EXIT_STAGE split"); + let result = runner::dispatch_split(&chain, [2, 2, 2], &input).unwrap(); + assert_eq!(result, expected, "split program CPU oracle"); + println!("CHAIN_EXIT checked_words=2048 guards=16 pieces={} scratch_dwords_per_group={}", chain.pieces.len(), chain.dwords_per_group); + } + #[test] fn dispatch_chain_payload_skips_middle_piece() { check_persistent_payload(false); } diff --git a/docs/wave64-on-wave32.md b/docs/wave64-on-wave32.md index c11d203537..8b84fb48b7 100644 --- a/docs/wave64-on-wave32.md +++ b/docs/wave64-on-wave32.md @@ -72,6 +72,13 @@ SGPRs of both halves and the tests fail if they ever differ. are resident on one SM / CU) but not necessarily on WARP. `XCL_WAVE64_SPIN=1` forces this variant everywhere (the test suite passes with it too). +For direct compute dispatches split across pipelines, a group of full console waves can +carry the exchange state through scratch. A signal and its bounded wait stay in one piece. +All threads meet at the piece exit and copy the arrival counters and both banks of slots. +The next piece assigns logical thread IDs again, restores the shared words and synchronises +before following each lane's continuation. Each console wave keeps its own exchange count, +including when other waves skip the piece. Programs using guest LDS stay on the whole pipeline. + A console wave whose upper half does not exist (group of 32 or 96 threads) exchanges with nobody: the missing lanes count as inactive (ballot bits 0), exactly as on the console. The GS phase of ES+GS runs in the lower half only (≤ 21 primitives), likewise without a partner.