diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index 327f07aa8c..f754479183 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -16,6 +16,10 @@ //! our null command-list limits keep from running. #![allow(clippy::not_unsafe_ptr_arg_deref)] +#[cfg(all(test, windows, feature = "diagnostics"))] +#[path = "pipeline/wave64_runtime_tests.rs"] +mod wave64_runtime_tests; + use std::collections::HashMap; use std::mem::offset_of; use std::sync::{Arc, Mutex, OnceLock}; diff --git a/crates/victory-gpu/src/pipeline/wave64_runtime_tests.rs b/crates/victory-gpu/src/pipeline/wave64_runtime_tests.rs new file mode 100644 index 0000000000..f63daba401 --- /dev/null +++ b/crates/victory-gpu/src/pipeline/wave64_runtime_tests.rs @@ -0,0 +1,102 @@ +//! Smoke test for the runtime's guest compute pipeline, using only the +//! synthetic containers from victory-shader's wave64_auto_group tests. + +use super::*; +use std::time::{Duration, Instant}; +use victory_shader::{Container, FourCC}; +use windows::Win32::Graphics::Direct3D12::*; +use windows::core::Interface; + +#[test] +#[ignore = "requires pre-generated synthetic wave64 containers, a wave32 GPU and D3D12 Graphics Tools"] +fn wave64_runtime_selects_paired_compute_pipelines() { + let fixtures = std::path::PathBuf::from( + std::env::var_os("VICTORY_TEST_WAVE64_DIR").expect("synthetic fixture directory"), + ); + let device = &crate::host::host().expect("runtime D3D12 host").device; + let mut caps = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default(); + // SAFETY: The feature query receives the matching description. + unsafe { + device + .CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS1, + (&raw mut caps).cast(), + size_of_val(&caps) as u32, + ) + .expect("wave capabilities"); + } + assert_eq!((caps.WaveLaneCountMin, caps.WaveLaneCountMax), (32, 32)); + let messages: ID3D12InfoQueue = device.cast().expect("run with D3D12 debug enabled"); + // Initialize the runtime's descriptor limit before observing PSO diagnostics. + // Its one-time probe deliberately attempts a heap larger than NVIDIA allows. + crate::descriptor::host::probe_view_limit(); + // SAFETY: This isolated test owns the queue's observation window. + unsafe { messages.ClearStoredMessages() }; + for threads in [64, 128] { + let bytes = std::fs::read(fixtures.join(format!("wave64-{threads}.cdxil"))) + .expect("read the generated synthetic container"); + let desc = ComputeHead { + root: std::ptr::null(), + stage: Bytecode { + code: bytes.as_ptr(), + size: bytes.len(), + }, + }; + let mut guest = std::ptr::null(); + assert_eq!( + create_compute(std::ptr::null(), &desc, &PIPELINE_IIDS[0], &mut guest), + object::S_OK, + ); + let deadline = Instant::now() + Duration::from_secs(10); + loop { + if let Some(made) = host_pipeline(guest) { + assert!(made.compute); + break; + } + assert!( + Instant::now() < deadline, + "runtime PSO for {threads} guest threads" + ); + std::thread::sleep(Duration::from_millis(10)); + } + let translated = pipeline(guest).shaders[0] + .translated() + .expect("runtime translation"); + let dxil = Container::parse(&translated.host.dxil).expect("emitted DXIL"); + let psv = dxil.part(FourCC::PSV0).expect("pipeline state validation"); + // Four-byte size followed by the 36-byte prefix of PSVRuntimeInfo2. + let physical_x = u32::from_le_bytes(psv.data[40..44].try_into().unwrap()); + assert_eq!( + physical_x, + threads / 2, + "runtime did not select the paired form" + ); + eprintln!("runtime PSO: {threads} guest threads, {physical_x} physical threads"); + let release = object::slot:: u32>(guest, 0x10); + release(guest); + } + // SAFETY: The queue supplies each message's required size. usize storage + // provides enough alignment for the D3D12_MESSAGE header. + unsafe { + for index in 0..messages.GetNumStoredMessages() { + let mut size = 0; + messages.GetMessage(index, None, &mut size).unwrap(); + let mut store = vec![0usize; size.div_ceil(size_of::())]; + let message = store.as_mut_ptr().cast::(); + messages + .GetMessage(index, Some(message), &mut size) + .unwrap(); + // A cold pipeline library can miss before the runtime builds + // the PSO. Both successful PSOs were required above. + if (*message).ID == D3D12_MESSAGE_ID_LOADPIPELINE_NAMENOTFOUND { + continue; + } + assert!( + (*message).Severity.0 > D3D12_MESSAGE_SEVERITY_WARNING.0, + "{:?}: {}", + (*message).ID, + std::ffi::CStr::from_ptr((*message).pDescription.cast()).to_string_lossy(), + ); + } + } +} diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 282d7c0757..a745253d5a 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -109,6 +109,8 @@ mod valu_tests; mod waterfall_tests; #[cfg(all(test, windows))] mod wave64_tests; +#[cfg(all(test, windows))] +mod wave64_group_tests; mod wave; use crate::dxbc::{Container, FourCC}; @@ -429,6 +431,24 @@ fn emit_any( io: &io::Io, res: &resource::Resources, ) -> Result { + // A masked first-lane read can elect a lane in the other half, even + // when no instruction uses an explicit lane index. Try the exact paired + // form before accepting a host32 form for this case. + if native.stage == HwStage::Cs + && native.wave64 + && lower::host_max_wave() == 32 + && pairs_on() + && p.blocks.iter().enumerate().any(|(b, block)| { + block.insts.iter().enumerate().any(|(i, inst)| { + inst.name() == "v_readfirstlane_b32" + && st.guards[b][i].is_some() + && !inst.writes.first().is_some_and(|w| res.waterfall.reads.contains(&w.1)) + }) + }) + && let Ok((shader, _)) = paired(c, native, p, io, res) + { + return Ok(shader); + } let r = emit_forms(c, native, p, st, io, res); // A console wave64 compute program on a host of 32-lane waves that no form above gives // the host (it still asks for 64-lane waves, or does not translate): once more in the diff --git a/crates/victory-shader/src/emit/wave64_group_tests.rs b/crates/victory-shader/src/emit/wave64_group_tests.rs new file mode 100644 index 0000000000..31efec0b1d --- /dev/null +++ b/crates/victory-shader/src/emit/wave64_group_tests.rs @@ -0,0 +1,294 @@ +//! Synthetic two-wave contract for Marvisak/VIctory#2688. The LDS loop +//! is adapted from PiloteCode's GPL-3.0 fixture in fxceless/victory-fork#854. + +use super::host::{Dispatch, Host, Root, View}; +use super::validator; +use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, +}; +use crate::{Container, FourCC, dxbc::u32_at}; +use windows::Win32::Graphics::Direct3D12::*; +use windows::core::Interface; + +const EXEC: u32 = 126; +const VCC: u32 = 106; +const GUARD: usize = 8; +const OUTPUTS: usize = 7; + +const fn k(value: u32) -> u32 { + 128 + value +} +const fn v(reg: u32) -> u32 { + 256 + reg +} +const fn mov(dst: u32, src: u32) -> u32 { + 0x7E00_0200 | dst << 17 | src +} +const fn sop1(op: u32, dst: u32, src: u32) -> u32 { + 0xBE80_0000 | dst << 16 | op << 8 | src +} +const fn alu(op: u32, dst: u32, left: u32, right: u32) -> u32 { + op << 25 | dst << 17 | right << 9 | left +} +const fn cmp(op: u32, left: u32, right: u32) -> u32 { + 0x7C00_0000 | op << 17 | right << 9 | left +} +const fn ds(op: u32, dst: u32, address: u32, data: u32) -> [u32; 2] { + [0xD800_0000 | op << 18, dst << 24 | data << 8 | address] +} + +fn guest(threads: u32) -> NativeProgram { + let mut words = vec![ + alu(0x16, 1, k(6), 0), // v1: logical wave index + alu(0x1B, 2, k(63), 0), // v2: logical lane index + alu(0x1A, 11, k(2), 1), // v11: byte address of wave's LDS counter + mov(12, k(0)), + sop1(4, 22, EXEC), + cmp(0xD2, k(0), 2), // only logical lane 0 initializes this wave's counter + ]; + words.extend(ds(0x0D, 0, 11, 12)); + words.extend([ + sop1(4, EXEC, 22), + alu(0x1B, 3, k(3), 2), + alu(0x25, 3, k(1), 3), + alu(0x25, 3, v(1), 3), // rounds = 1 + (lane & 3) + wave + mov(4, k(0)), + mov(13, k(1)), + sop1(4, 20, EXEC), + alu(0x25, 4, v(2), 4), // loop: accumulate the lane number + ]); + words.extend(ds(0, 0, 11, 13)); // ds_add_u32: add one per participating lane + words.extend([ + alu(0x25, 3, 193, 3), // decrement remaining rounds + cmp(0xC5, k(0), 3), + 0x8000_0000 | 0x0F << 23 | EXEC << 16 | VCC << 8 | EXEC, // s_and_b64 exec, exec, vcc + 0xBF89_FFF9, // s_cbranch_execnz loop + sop1(4, EXEC, 20), + ]); + words.extend(ds(0x36, 5, 11, 0)); // v5: total from own wave + + // Wave 0 first reads lane 40 and then lane 20. Wave 1 selects lane 24 + // and then lane 36, so the same instruction selects opposite halves. + for (threshold, op, scalar, dest) in [(39, 0x26, 6, 6), (19, 0x25, 7, 9)] { + words.extend([ + alu(0x1A, 14, k(4), 1), + alu(op, 14, k(threshold), 14), + sop1(4, 24, EXEC), + cmp(0xD1, v(14), 2), // v_cmpx_lt_u32 threshold, lane + 0x7E00_0400 | scalar << 17 | v(4), // v_readfirstlane_b32 + sop1(4, EXEC, 24), + mov(dest, scalar), + ]); + } + + // Write one value per lane into its own wave's region, then read its + // opposite half. The guest needs ordering within its wave without s_barrier. + words.extend([ + alu(0x1A, 10, k(2), 0), + alu(0x1D, 14, k(32), 0), + alu(0x1A, 14, k(2), 14), + ]); + let [op, args] = ds(0x0D, 0, 10, 4); + words.extend([op | 8, args]); + let [op, args] = ds(0x36, 10, 14, 0); + words.extend([op | 8, args]); + + if threads == 128 { + words.extend([0xBF8A_0000, alu(0x1D, 14, k(4), 11)]); // s_barrier, then other wave's LDS + words.extend(ds(0x36, 7, 14, 0)); + } else { + words.push(mov(7, v(5))); + } + words.extend([alu(0x1A, 15, k(2), 0), 0xBE85_0380]); // output offset and table address high + for (slot, reg) in [4, 5, 6, 9, 7, 10, 0].into_iter().enumerate() { + words.extend([ + 0x3D << 26 | 0x02 << 18 | 8 << 6 | 2, // s_load_dwordx4 s[8:11], s[4:5] + 125 << 25 | (slot as u32 * 32), + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xE070_1000, + 0x8002_0000 | reg << 8 | 15, // buffer_store_dword v, v15, s[8:11], 0 offen + ]); + } + words.push(0xBF81_0000); + NativeProgram { + stage: HwStage::Cs, + wave64: true, + vgprs: 16, + layout: vec![RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 4, + slot: 0, + }], + used: (0..OUTPUTS as u32) + .map(|slot| UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: slot * 8, + lower_bound: slot, + stride: 0, + dwords: 4, + user_data: 4, + slot: 0, + }) + .collect(), + io: StageIo::Cs(ComputeIo { + rsrc2: 5 << 1 | 2 << 15, // s0..s4 and 1 KiB of LDS + threads: [threads, 1, 1], + }), + code: words.into_iter().flat_map(u32::to_le_bytes).collect(), + } +} + +fn oracle(threads: u32, thread: u32) -> [u32; OUTPUTS] { + let wave = thread / 64; + let lane = thread % 64; + let lane_sum = |lane| lane * (1 + (lane % 4) + wave); + let wave_total = |wave| (0..64).map(|lane| 1 + lane % 4 + wave).sum(); + [ + lane_sum(lane), + wave_total(wave), + lane_sum([40, 24][wave as usize]), + lane_sum([20, 36][wave as usize]), + wave_total(if threads == 128 { 1 - wave } else { wave }), + lane_sum(lane ^ 32), + thread, + ] +} + +fn debug_warnings(queue: &ID3D12InfoQueue) -> Vec { + // SAFETY: All read buffers are aligned and sized by the info queue. + unsafe { + (0..queue.GetNumStoredMessages()) + .filter_map(|index| { + let mut size = 0; + queue.GetMessage(index, None, &mut size).unwrap(); + let mut words = vec![0usize; size.div_ceil(size_of::())]; + let message = words.as_mut_ptr().cast::(); + queue.GetMessage(index, Some(message), &mut size).unwrap(); + let message = &*message; + (message.Severity.0 <= D3D12_MESSAGE_SEVERITY_WARNING.0).then(|| { + std::ffi::CStr::from_ptr(message.pDescription.cast()) + .to_string_lossy() + .into_owned() + }) + }) + .collect() + } +} + +fn run(threads: u32) { + static DEBUG: std::sync::Once = std::sync::Once::new(); + // SAFETY: These opt-in tests run in isolation and enable the debug layer + // before creating the first device in the test process. + DEBUG.call_once(|| unsafe { + let mut debug: Option = None; + D3D12GetDebugInterface(&mut debug).expect("D3D12 Graphics Tools"); + let debug = debug.expect("D3D12 debug interface"); + debug.EnableDebugLayer(); + debug + .cast::() + .unwrap() + .SetEnableGPUBasedValidation(true); + }); + let host = Host::new(false).expect("hardware D3D12 adapter"); + // SAFETY: The feature query writes only into the matching D3D12 description. + let mut caps = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default(); + unsafe { + host.device + .CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS1, + (&raw mut caps).cast(), + size_of_val(&caps) as u32, + ) + .expect("wave capabilities"); + } + assert_eq!((caps.WaveLaneCountMin, caps.WaveLaneCountMax), (32, 32)); + let queue: ID3D12InfoQueue = host.device.cast().expect("D3D12 info queue"); + // SAFETY: The queue belongs to this test's device. + unsafe { queue.ClearStoredMessages() }; + // Use the same host capability as the runtime and enter through the + // public translator. Neither the paired form nor a wave override is used. + super::set_host_max_wave(caps.WaveLaneCountMax); + let bytes = crate::native::tests::compute_uav_container(&guest(threads)); + let mut shader = super::translate(&bytes).expect("translate synthetic wave64 container"); + validator::Validator::load(validator::Validator::default_path().as_deref()) + .expect("DXIL validator") + .validate(&mut shader.dxil) + .expect("validate synthetic DXIL"); + let (root, pso) = host.compute_pipeline(&shader).unwrap_or_else(|error| { + panic!( + "compute PSO: {error}; D3D12 validation: {:#?}", + debug_warnings(&queue) + ); + }); + let views = [(); OUTPUTS].map(|()| View::RawUav(threads + GUARD as u32)); + let data = vec![0; shader.user_data_dwords().max(1) as usize]; + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(data))], + views: &views, + samplers: &[], + groups: [1, 1, 1], + }, + ) + .expect("dispatch and readback"); + let warnings = debug_warnings(&queue); + assert!(warnings.is_empty(), "D3D12 validation: {warnings:#?}"); + assert_eq!(out.len(), OUTPUTS); + for (slot, words) in out.iter().enumerate() { + assert_eq!(words.len(), threads as usize + GUARD); + for thread in 0..threads { + assert_eq!( + words[thread as usize], + oracle(threads, thread)[slot], + "UAV {slot}, thread {thread}" + ); + } + assert_eq!(&words[threads as usize..], &[0; GUARD], "UAV {slot} guard"); + } + let container = Container::parse(&shader.dxil).expect("emitted DXIL container"); + let psv = container + .part(FourCC::PSV0) + .expect("pipeline state validation"); + assert_eq!( + u32_at(psv.data, 40).unwrap(), + threads / 2, + "physical thread count" + ); + eprintln!( + "{threads} guest threads: {OUTPUTS} UAVs match CPU, guards intact, no D3D12 warnings/errors" + ); +} + +// Select only these tests so GPU validation is enabled before device creation. +#[test] +#[ignore = "requires a wave32 GPU, Graphics Tools, and DXIL validator"] +fn wave64_auto_group_64() { + run(64); +} + +#[test] +#[ignore = "requires a wave32 GPU, Graphics Tools, and DXIL validator"] +fn wave64_auto_group_128() { + run(128); +} + +#[test] +#[ignore = "exports synthetic inputs for the runtime smoke test"] +fn wave64_write_runtime_fixtures() { + let dir = std::path::PathBuf::from( + std::env::var_os("VICTORY_TEST_WAVE64_DIR").expect("synthetic fixture directory"), + ); + std::fs::create_dir_all(&dir).expect("create synthetic fixture directory"); + for threads in [64, 128] { + let bytes = crate::native::tests::compute_uav_container(&guest(threads)); + std::fs::write(dir.join(format!("wave64-{threads}.cdxil")), &bytes) + .expect("write synthetic container"); + } +} diff --git a/crates/victory-shader/src/native.rs b/crates/victory-shader/src/native.rs index 4c267e17c7..8db227535e 100644 --- a/crates/victory-shader/src/native.rs +++ b/crates/victory-shader/src/native.rs @@ -718,7 +718,7 @@ fn bytes(data: &[u8], offset: u64, len: u64) -> Option<&[u8]> { } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; const VS_CODE: [u8; 8] = [1, 2, 3, 4, 5, 6, 7, 8]; @@ -790,6 +790,50 @@ mod tests { out } + /// A synthetic compute container with one table of UAV descriptors. + #[cfg(windows)] + pub(crate) fn compute_uav_container(native: &NativeProgram) -> Vec { + let StageIo::Cs(io) = &native.io else { panic!("expected compute") }; + let mut blob = fssm(&[(HwStage::Cs, &native.code)]); + let stage = stage_data_at(&blob, HwStage::Cs); + let record = stage - RECORD_SIZE as usize; + let put32 = |bytes: &mut [u8], at, word: u32| { + bytes[at..][..4].copy_from_slice(&word.to_le_bytes()); + }; + let put64 = |bytes: &mut [u8], at, word: u64| { + bytes[at..][..8].copy_from_slice(&word.to_le_bytes()); + }; + put32(&mut blob, record + RECORD_FLAGS, if native.wave64 { 0 } else { FLAG_WAVE32 }); + put32(&mut blob, record + RECORD_REGS, u32::from(native.vgprs)); + put32(&mut blob, stage + CS_RSRC2, io.rsrc2); + for (axis, count) in io.threads.into_iter().enumerate() { + put32(&mut blob, stage + CS_THREADS + axis * 4, count); + } + let layout = (blob.len() - FSSM_HEADER) as u64; + put64(&mut blob, record + RECORD_LAYOUT, layout); + put32(&mut blob, record + RECORD_COUNTS, native.layout.len() as u32); + for param in &native.layout { + assert_eq!(param.root, RootType::Table); + for field in [3, param.table_offset_dwords, param.sgprs, param.base_register] { + blob.extend_from_slice(&field.to_le_bytes()); + } + blob.extend_from_slice(&[param.user_data, param.slot, 0, 0]); + } + let used = (blob.len() - FSSM_HEADER) as u64; + put64(&mut blob, record + RECORD_USED, used); + put32(&mut blob, record + RECORD_COUNTS + 4, native.used.len() as u32); + for uav in &native.used { + assert_eq!((uav.kind, uav.root), (ResourceType::Uav, RootType::Table)); + for field in [0x0303, uav.table_offset_dwords, uav.lower_bound, uav.stride] { + blob.extend_from_slice(&field.to_le_bytes()); + } + blob.extend_from_slice(&[uav.dwords, uav.user_data, uav.slot, 0]); + } + let payload_size = (blob.len() - FSSM_HEADER) as u64; + put64(&mut blob, 8, payload_size); + crate::dxbc::build(&[(crate::FourCC::DXIL, &part(&[(KIND_NATIVE, &xbch(&blob))]))]) + } + /// `DXIL` part data: program header, XDAT index, then the blobs. fn part(blobs: &[(u32, &[u8])]) -> Vec { let mut out = vec![0u8; XDAT_OFFSET];