diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 2f817a809f..4ee85e736a 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -4758,12 +4758,13 @@ impl Em { } } - /// Split wave64: meet through bounded arrival counters (`XCL_X_SPIN 1`) by default so - /// divergent wave32 halves can never permanently deadlock a GPU SM at an unbounded - /// `GroupMemoryBarrierWithGroupSync()`. Set `XCL_WAVE64_SPIN=0` to force group barriers - /// for 1-wave64 groups. + /// Split wave64: how the halves meet (`XCL_X_SPIN`, `x64_spin_for`). fn x64_spin(&self) -> bool { - self.x64_threads() > 64 || std::env::var("XCL_WAVE64_SPIN").map_or(true, |v| v.trim() != "0") + x64_spin_for( + self.x64_threads(), + std::env::var("XCL_WAVE64_SPIN").ok().as_deref(), + std::env::var("XCL_WAVE64_BARRIER").ok().as_deref(), + ) } /// The console LDS block (`xcl_lds`) is declared before the split-wave64 prelude, which @@ -6095,6 +6096,30 @@ void st_bytes(uint a, uint4 r, uint n) { uint dst_sel(uint4 c, uint sel, bool isint) { return select(sel == 0u, 0u, select(sel == 1u, select(isint, 1u, 0x3F800000u), pick4(c, (sel - 4u) & 3u))); } "#; +/// Split wave64: whether the halves of a group of `threads` meet through bounded arrival +/// counters (`XCL_X_SPIN 1`, the default) rather than a group barrier. Several console waves per +/// group (more than 64 threads) always use the counters: a group barrier would wait for the other +/// console waves too, whose control flow may differ. +/// +/// A group of one console wave can meet at a group barrier instead: its two halves are the whole +/// group and take the same branches (on exchanged, wave-uniform state), and the barrier costs a +/// fraction of the counters (#1244). It is opt-in, because halves that do end up apart (a plain +/// scalar load that sees two values, `docs/wave64-on-wave32.md` hazard 1) would then wait for +/// each other for good and hang the dispatch, where the counters give up after a bounded wait. +/// `barrier` (`XCL_WAVE64_BARRIER`) set to anything but empty or `0` asks for it, and so does +/// `spin` (`XCL_WAVE64_SPIN`) `0`; `spin` set to any other value (including empty) forces the +/// counters and wins over `barrier`. +pub(super) fn x64_spin_for(threads: u32, spin: Option<&str>, barrier: Option<&str>) -> bool { + if threads > 64 { + return true; + } + match spin.map(str::trim) { + Some("0") => false, + Some(_) => true, + None => !barrier.map(str::trim).is_some_and(|v| !v.is_empty() && v != "0"), + } +} + /// A console wave64 as two hardware wave32 halves of one thread group (docs/wave64-on-wave32.md): /// per-lane code is unchanged, and the halves meet ("exchange") wherever a value has to be /// the whole wave's – masks, lane reads, coherent scalar loads – so both hold the same SGPRs diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index b8b0cde0f1..03a4abb1cb 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -905,7 +905,7 @@ fn cached_shader( } fn cache_allowed(stage: Stage, present: impl Fn(&str) -> bool) -> bool { - !["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_X64_ALL_MASKS", "XCL_WAVE64_SPIN", "XCL_DXIL_NO_OPT"] + !["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_X64_ALL_MASKS", "XCL_WAVE64_SPIN", "XCL_WAVE64_BARRIER", "XCL_DXIL_NO_OPT"] .iter() .any(|name| present(name)) && (stage != Stage::Pixel @@ -1997,7 +1997,7 @@ mod shader_cache_tests { #[test] fn shader_cache_bypasses_debug_overrides() { - for name in ["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_X64_ALL_MASKS", "XCL_WAVE64_SPIN", "XCL_DXIL_NO_OPT"] { + for name in ["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_X64_ALL_MASKS", "XCL_WAVE64_SPIN", "XCL_WAVE64_BARRIER", "XCL_DXIL_NO_OPT"] { assert!(!cache_allowed(Stage::Compute, |v| v == name)); assert!(!cache_allowed(Stage::Vertex, |v| v == name)); assert!(!cache_allowed(Stage::Pixel, |v| v == name)); diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 0b018edc36..a2124836df 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -6904,6 +6904,56 @@ fn mesh_split_wave64_form() { assert!(super::translate_mesh(&lane, ms, true, true, 1).unwrap().hlsl.contains("xcl_x_rla_uniform(")); } +/// How the split halves meet (`x64_spin_for`): bounded arrival counters by default; a group of +/// one console wave meets at a group barrier only on request (`XCL_WAVE64_BARRIER=1` or +/// `XCL_WAVE64_SPIN=0`), and a group of several console waves never does. +#[test] +fn split_wave64_meet_form_by_group_size() { + use super::emit::x64_spin_for; + use super::CsInterface; + for threads in [16u32, 32, 40, 64] { + assert!(x64_spin_for(threads, None, None), "{threads}: counters by default"); + assert!(x64_spin_for(threads, None, Some("")), "{threads}: XCL_WAVE64_BARRIER empty"); + assert!(x64_spin_for(threads, None, Some("0")), "{threads}: XCL_WAVE64_BARRIER=0"); + assert!(!x64_spin_for(threads, None, Some("1")), "{threads}: XCL_WAVE64_BARRIER=1"); + assert!(!x64_spin_for(threads, None, Some(" 1 ")), "{threads}: XCL_WAVE64_BARRIER=' 1 '"); + assert!(!x64_spin_for(threads, Some("0"), None), "{threads}: XCL_WAVE64_SPIN=0 (as before)"); + assert!(!x64_spin_for(threads, Some(" 0 "), None), "{threads}: XCL_WAVE64_SPIN=' 0 '"); + assert!(x64_spin_for(threads, Some("1"), None), "{threads}: XCL_WAVE64_SPIN=1"); + assert!(x64_spin_for(threads, Some(""), None), "{threads}: XCL_WAVE64_SPIN empty (as before)"); + // forcing the counters wins over asking for the barrier + assert!(x64_spin_for(threads, Some("1"), Some("1")), "{threads}: SPIN=1 beats BARRIER=1"); + assert!(!x64_spin_for(threads, Some("0"), Some("1")), "{threads}: both ask for the barrier"); + } + for threads in [65u32, 96, 128, 256, 1024] { + for spin in [None, Some("0"), Some("1")] { + for barrier in [None, Some("1")] { + assert!(x64_spin_for(threads, spin, barrier), "{threads}, {spin:?}, {barrier:?}: several console waves always spin"); + } + } + } + // the emitted form: the default is hard-coded (counters everywhere), so these checks run + // only when neither variable is set + let env_set = std::env::var_os("XCL_WAVE64_SPIN").is_some() || std::env::var_os("XCL_WAVE64_BARRIER").is_some(); + let lane = prog(&[("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 0), ("SRC0", V)], None)]); + for dims in [[64u32, 1, 1], [8, 8, 1], [4, 4, 4], [40, 1, 1], [32, 1, 1], [16, 1, 1], [256, 1, 1], [8, 8, 4]] { + let threads = dims.iter().product::(); + let cs = CsInterface { threads: dims, user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let t = translate(&lane, &Options { mode: Mode::Compute(cs), wave64: true, split_wave64: true, ..Default::default() }).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + assert!(t.hlsl.contains(&format!("#define XCL_X_THREADS {threads}u")), "{dims:?}"); + if threads > 64 || !env_set { + assert!(t.hlsl.contains("#define XCL_X_SPIN 1\n"), "{dims:?}"); + } + assert!(t.hlsl.contains("xcl_x_rla_uniform("), "{dims:?}"); + } + // a half without a partner (32 threads or fewer: `xcl_xn == 0`) leaves before either form + let t = translate(&lane, &Options { mode: Mode::Compute(CsInterface { threads: [32, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }), wave64: true, split_wave64: true, ..Default::default() }).unwrap(); + let meet = &t.hlsl[t.hlsl.find("bool xcl_x_meet()").unwrap()..]; + let (leave, spin, barrier) = (meet.find("if (xcl_xn == 0u) return false;").unwrap(), meet.find("#if XCL_X_SPIN").unwrap(), meet.find("GroupMemoryBarrierWithGroupSync();").unwrap()); + assert!(leave < spin && spin < barrier); +} + /// Operations whose result spans both 32-lane halves of a wave64 – what the split form /// exchanges: masks with bits in either half (counted, scanned, branched on), readlane / /// readfirstlane of a lane in the other half, ds_bpermute across the halves, a GLC scalar @@ -7380,8 +7430,13 @@ fn gpu_split_wave64_waves_diverge() { let opt = on_gpu(Options { mode: Mode::Compute(cs), wave64: true, ..Default::default() }); let t = translate(&p, &opt).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); - if runner::split_wave64() && std::env::var("XCL_WAVE64_SPIN").map_or(true, |v| v.trim() != "0") { - assert!(t.hlsl.contains("[WaveSize(32)]") && t.hlsl.contains("#define XCL_X_SPIN 1"), "{dims:?}"); + if runner::split_wave64() { + assert!(t.hlsl.contains("[WaveSize(32)]"), "{dims:?}"); + // counters, unless a variable asks for the barrier in the group of one console wave + // (64 threads) + if threads > 64 || !(std::env::var_os("XCL_WAVE64_SPIN").is_some() || std::env::var_os("XCL_WAVE64_BARRIER").is_some()) { + assert!(t.hlsl.contains("#define XCL_X_SPIN 1\n"), "{dims:?}"); + } } let dxil = direct_or(&p, &opt, dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}"))); let base = 0x100usize; @@ -7403,6 +7458,59 @@ fn gpu_split_wave64_waves_diverge() { } } +/// Groups of one console wave (64 threads or fewer), which meet at a group barrier when split +/// and `XCL_WAVE64_BARRIER=1` asks for it (`x64_spin_for`; counters otherwise): an exchange, then odd groups end early (`s_endpgm` on a scalar branch), +/// even ones exchange once more and store. Neither half may be left waiting at the barrier +/// (that would hang the dispatch), and partial groups (40, 48 threads) meet like full ones. +#[test] +fn gpu_split_wave64_one_wave_groups_end_early() { + if !gpu_ready() { + return; + } + use super::{dxc, CsInterface}; + // s0 = output base, s2 = group id + let p = prog(&[ + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 255), ("VSRC1", 0)], Some(1000)), // v1 = 1000 + thread + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 0)], Some(40)), // vcc = threads 0..39 + ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 106)], None), + ("S_AND_B32", "ENC_SOP2", &[("SDST", 21), ("SSRC0", 2), ("SSRC1", 129)], None), // scc = odd group + ("S_CBRANCH_SCC0", "ENC_SOPP", &[("SIMM16", 1)], None), + ("S_ENDPGM", "ENC_SOPP", &[], None), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 21), ("SRC0", V + 1), ("SRC1", 165)], None), // lane 37 (upper half) + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 20)], None), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 21), ("VSRC1", 4)], None), + ("S_LSHL_B32", "ENC_SOP2", &[("SDST", 16), ("SSRC0", 2), ("SSRC1", 134)], None), // group · 64 + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 16), ("VSRC1", 0)], None), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 130), ("VSRC1", 7)], None), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 0), ("VSRC1", 7)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 128)], None), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 7), ("DATA", 4), ("SADDR", 0x7D)], None), + ]); + for threads in [64u32, 48, 40] { + let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + let opt = on_gpu(Options { mode: Mode::Compute(cs), wave64: true, ..Default::default() }); + let t = translate(&p, &opt).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + if runner::split_wave64() && std::env::var_os("XCL_WAVE64_SPIN").is_none() { + // one console wave per group: counters, or a group barrier when asked for + let barrier = std::env::var("XCL_WAVE64_BARRIER").is_ok_and(|v| !v.trim().is_empty() && v.trim() != "0"); + assert!(t.hlsl.contains(&format!("#define XCL_X_SPIN {}\n", u8::from(!barrier))), "{threads}"); + } + let dxil = direct_or(&p, &opt, dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}"))); + let base = 0x100usize; + let groups = 64usize; + let mut io = vec![0u32; 128]; + io[0] = base as u32; + let out = runner::dispatch(&dxil, [groups as u32, 1, 1], &io, &vec![0u32; (base + groups * 64 * 4) / 4]).unwrap(); + for g in 0..groups { + for tid in 0..64usize { + let want = if g % 2 == 1 || tid >= threads as usize { 0 } else { 40 + 1037 }; + assert_eq!(out[(base + (g * 64 + tid) * 4) / 4], want, "{threads} threads, group {g} thread {tid}"); + } + } + } +} + /// What the split wave64 form costs (`cargo test --release -- --ignored bench_split_wave64 /// --nocapture`): a loop of a few VALU instructions and one mask (`v_cmp`, an exchange in the /// split form), plus a readfirstlane (another exchange) in the second variant, as a wave32 @@ -7473,9 +7581,9 @@ fn bench_split_wave64() { t.sort_by(f64::total_cmp); ms.push(t[t.len() / 2]); } - // the form `x64_spin` picks: counters for groups of more than one console wave, - // and by default for one as well (`XCL_WAVE64_SPIN=0`: a group barrier) - let spin = threads > 64 || std::env::var("XCL_WAVE64_SPIN").map_or(true, |v| v.trim() != "0"); + // the form `x64_spin` picks: counters, or a group barrier in a group of one console + // wave when `XCL_WAVE64_BARRIER=1` asks for it + let spin = super::emit::x64_spin_for(threads, std::env::var("XCL_WAVE64_SPIN").ok().as_deref(), std::env::var("XCL_WAVE64_BARRIER").ok().as_deref()); let form = if runner::split_wave64() { if spin { "split, counter-paired" } else { "split, barrier" } } else { "native" }; println!( "v_cmp + v_cndmask{}: {exchanges} exchange(s) / iteration, {threads} threads per group, 2^18 threads x {iterations} iterations: wave32 {:.1} ms, wave64 ({form}) {:.1} ms = {:.2}x", diff --git a/docs/wave64-on-wave32.md b/docs/wave64-on-wave32.md index c11d203537..bb1a1eaa5f 100644 --- a/docs/wave64-on-wave32.md +++ b/docs/wave64-on-wave32.md @@ -51,11 +51,15 @@ SGPRs of both halves and the tests fail if they ever differ. ### Synchronisation -* **One console wave per group** (≤ 64 threads: kernel mode, most compute, ES+GS): - `GroupMemoryBarrierWithGroupSync` between writing and reading the slot. All hardware +* **One console wave per group** (≤ 64 threads: kernel mode, most compute, ES+GS): the + counters below by default. `XCL_WAVE64_BARRIER=1` (or `XCL_WAVE64_SPIN=0`) selects + `GroupMemoryBarrierWithGroupSync` between writing and reading the slot instead. All hardware waves of the group are the two halves of the same console wave, which execute the same sequence of exchanges, so every barrier is reached by both. Portable (no forward-progress - assumption) and cheap. + assumption) and cheap, but not bounded: halves that do end up apart (hazard 1: a plain + scalar load that sees two values) wait for each other for good and the dispatch hangs until + a TDR, where the counters give up and finish with wrong output. That is why it is opt-in. + `XCL_WAVE64_SPIN=1` (any value but `0`) wins over `XCL_WAVE64_BARRIER`. * **Several console waves per group** (mesh: 128 threads, compute > 64 threads): a group barrier would also wait for the *other* console waves, whose control flow may differ (wave index, per-wave data). Each pair instead meets through groupshared arrival counters: @@ -69,8 +73,9 @@ SGPRs of both halves and the tests fail if they ever differ. pair – should not happen, see hazards), the wave stops exchanging (`xcl_x_dead`) and finishes with half-local values instead of hanging the GPU until a TDR. This relies on co-resident waves of one group making progress, which holds on GPUs (all waves of a group - 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). + are resident on one SM / CU) but not necessarily on WARP. Groups of one console wave use it + too unless `XCL_WAVE64_BARRIER=1` asks for the barrier; `XCL_WAVE64_SPIN=1` forces it + everywhere (the test suite passes with it too). 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