From 565ab8517ed44f19a3974967a7e388a4c7efd9be Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 12:49:12 -0600 Subject: [PATCH 1/2] Max, min, legacy products, medians and fractions as the RDNA card's own (VICTORY_RDNA_FLOAT, on; 0: spelled out as before) The console's v_max/v_min (seven host operations each, for the order of the two zeros), v_mul_legacy (a product, two comparisons, an or and a select; two thirds of all products of the lighting program), v_med3 and v_fract are written as the one operation the driver makes the same instruction of, where the host is an AMD card with waves of 32 and 64. Checked on the RX 7900 XTX against the spelled-out forms with zeros, infinities and NaN (a legacy product's zero may have the other sign). RX 7900 XTX, yard capture replayed turn by turn with and without (12 loops each): dispatches and draws 18.41 -> 17.58 ms, the lists' 29.2 -> 28.4 of a 36.6 ms frame; 0.4 of it without the legacy products. The picture is the same (79 dB; two replays of one set differ by 68). A product that is only a product would give 0.65 ms more and NaN where the console has 0. Measured and left out (nothing): v_mad as one multiply-add, fast reciprocals, scalar loads of four dwords at once, buffers picked from the heap read without asking for their kind (0.12 ms), a wave size for every compute program (32: +0.26 ms, 64: +0.1, the console's: +0.1), no barriers at all (0). Changes the translator: every shader is translated again. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 12 +++ crates/victory-gpu/src/indirect.rs | 2 +- crates/victory-shader/src/emit/bitcode/opt.rs | 76 +++++++++++++++++ crates/victory-shader/src/emit/lower.rs | 77 ++++++++++++++++- crates/victory-shader/src/emit/mod.rs | 56 +++++++++++- crates/victory-shader/src/emit/probe_tests.rs | 74 ++++++++++++++++ crates/victory-shader/src/emit/valu_tests.rs | 85 +++++++++++++++++++ 7 files changed, 377 insertions(+), 5 deletions(-) create mode 100644 crates/victory-shader/src/emit/probe_tests.rs diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 507a79d..8cee056 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -921,6 +921,9 @@ fn create() -> windows::core::Result { { tracing::info!(min = o1.WaveLaneCountMin, max = o1.WaveLaneCountMax, "host wave lanes"); victory_shader::emit::set_host_max_wave(o1.WaveLaneCountMax); + // (RDNA has waves of 32 and 64, the vendor's older cards of 64 alone.) + let amd = crate::indirect::amd(&device); + victory_shader::emit::set_host_rdna(amd && o1.WaveLaneCountMin == 32 && o1.WaveLaneCountMax == 64); } let messages = debug .then(|| device.cast::().ok()) @@ -968,6 +971,15 @@ fn create() -> windows::core::Result { } } +impl Host { + /// The driver's version, as the system counts it (0: not known). + pub(crate) fn driver(&self) -> i64 { + let adapter = self.adapter.as_ref(); + // SAFETY: a plain query. + adapter.map_or(0, |a| unsafe { a.CheckInterfaceSupport(&IDXGIDevice::IID) }.unwrap_or(0)) + } +} + /// DXGI may return hardware for `EnumWarpAdapter` (notably under Proton). /// Reject it before creating a device in diagnostics' software-only mode. pub(crate) fn warp_adapter() -> windows::core::Result { diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index b48b71d..d74b748 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -268,7 +268,7 @@ fn widest(amd: bool) -> u32 { } /// Whether `device` is an AMD card's. -fn amd(device: &ID3D12Device) -> bool { +pub(crate) fn amd(device: &ID3D12Device) -> bool { use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory2, DXGI_CREATE_FACTORY_FLAGS, IDXGIAdapter1, IDXGIFactory4}; // SAFETY: plain queries. unsafe { diff --git a/crates/victory-shader/src/emit/bitcode/opt.rs b/crates/victory-shader/src/emit/bitcode/opt.rs index 89dc8b7..4fb2940 100644 --- a/crates/victory-shader/src/emit/bitcode/opt.rs +++ b/crates/victory-shader/src/emit/bitcode/opt.rs @@ -399,6 +399,82 @@ impl Module { Some((bits, *x as u64 & mask(bits))) } + /// The bits of a 32-bit float that is a constant, given as one or as a + /// cast of an integer constant. + pub(crate) fn float_k(&self, v: V) -> Option { + let (v, cast) = match v { + V::Inst(i) => match self.insts[i as usize].op { + Op::Cast(Cast::Bitcast, x) => (x, true), + _ => return None, + }, + _ => (v, false), + }; + let V::Const(i) = v else { return None }; + match &self.consts[i as usize].1 { + Const::Float(bits) if !cast => Some(f32::from_bits(*bits)), + Const::Int(_) if cast => { + let (bits, x) = self.int_k(v)?; + (bits == 32).then_some(f32::from_bits(x as u32)) + } + _ => None, + } + } + + /// For a float that is a number and not an infinity whatever the program + /// reads: a power of two its magnitude does not pass. + pub(crate) fn bounded(&self, v: V, depth: u32) -> Option { + if let Some(k) = self.float_k(v) { + return k.is_finite().then(|| k.abs().max(1e-30).log2().ceil()); + } + let V::Inst(i) = v else { return None }; + let depth = depth.checked_sub(1)?; + let of = |v: V| self.bounded(v, depth); + // (A power that overflows, or might with rounding, is no bound.) + let held = |b: f32| (b < 126.0).then_some(b); + match &self.insts[i as usize].op { + Op::Cast(Cast::UiToFp | Cast::SiToFp, _) => Some(32.0), + Op::Cast(Cast::Bitcast, x) => match *x { + V::Inst(j) => match self.insts[j as usize].op { + Op::Cast(Cast::Bitcast, y) if self.type_of(y) == self.type_of(v) => of(y), + _ => None, + }, + _ => None, + }, + Op::Bin(Bin::Mul, a, b) => held(of(*a)? + of(*b)?), + Op::Bin(Bin::Add | Bin::Sub, a, b) => held(of(*a)?.max(of(*b)?) + 1.0), + Op::Select(_, a, b) => Some(of(*a)?.max(of(*b)?)), + Op::Call(_, args) => { + let (_, code) = self.int_k(*args.first()?)?; + match (code, &args[1..]) { + // Saturated, a fraction, a cosine or sine (of a number). + (7, [_]) => Some(0.0), + (6, [x]) => of(*x), + (22 | 12 | 13, [x]) => of(*x).map(|_| 0.0), + (26..=29, [x]) => held(of(*x)? + 1.0), + // Of two numbers; or one of them the other way round: the + // minimum (36) of a constant and a maximum of another. + (35 | 36, [a, b]) => match (of(*a), of(*b)) { + (Some(x), Some(y)) => Some(x.max(y)), + _ => { + let other = if code == 35 { 36 } else { 35 }; + let (inner, k) = if self.float_k(*b).is_some() { (*a, *b) } else { (*b, *a) }; + let k = self.float_k(k).and_then(|_| of(k))?; + let V::Inst(j) = inner else { return None }; + let Op::Call(_, inner) = &self.insts[j as usize].op else { return None }; + let (_, code) = self.int_k(*inner.first()?)?; + let low = inner[1..].iter().find(|x| self.float_k(**x).is_some())?; + (code == other).then_some(())?; + Some(k.max(of(*low)?)) + } + }, + (46, [a, b, c]) => held((of(*a)? + of(*b)?).max(of(*c)?) + 1.0), + _ => None, + } + } + _ => None, + } + } + /// The constant `x` of the integer type `ty`, kept sign-extended as /// [`Module::i32`] and [`Module::bool`] keep theirs. fn k(&mut self, ty: Ty, bits: u32, x: u64) -> V { diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index d8387d5..6fa3cbb 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -1111,9 +1111,33 @@ fn own_bits_on() -> bool { } /// What the translator was told of the host, for a cache's key: the widest -/// wave, the view heap's limit and where the raw twins of its views start. -pub fn host_settings() -> [u32; 3] { - [host_max_wave(), super::shader::view_heap_limit(), super::shader::raw_views()] +/// wave, the view heap's limit, where the raw twins of its views start, and +/// what it writes for the console's own hardware. +pub fn host_settings() -> [u32; 4] { + [host_max_wave(), super::shader::view_heap_limit(), super::shader::raw_views(), host_rdna()] +} + +static HOST_RDNA: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Tells the translator that the host's shaders run on AMD RDNA hardware +/// ([`super::rdna_float`]). +pub fn set_host_rdna(on: bool) { + HOST_RDNA.store(on, std::sync::atomic::Ordering::Relaxed); +} + +#[cfg(test)] +thread_local! { + /// A test's choice for [`host_rdna`], for its thread only. + pub(super) static TEST_RDNA: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// The bits of [`super::rdna`] that count on this host. +pub(super) fn host_rdna() -> u32 { + #[cfg(test)] + if let Some(bits) = TEST_RDNA.get() { + return bits; + } + if HOST_RDNA.load(std::sync::atomic::Ordering::Relaxed) { super::rdna_float() } else { 0 } } /// The refusal of a first half of an interpolation whose result is read @@ -3674,6 +3698,9 @@ impl<'a> Lower<'a> { fn max_min(&mut self, max: bool, a: V, b: V) -> V { let c = self.cur; let r = self.binary(if max { 35 } else { 36 }, a, b); + if host_rdna() & super::rdna::MAX_MIN != 0 { + return r; + } let (ia, ib) = (self.as_int(a), self.as_int(b)); let either = self.s.m.bin(c, Bin::Or, ia, ib); let magnitude = self.s.m.i32(0x7FFF_FFFF); @@ -3807,6 +3834,25 @@ impl<'a> Lower<'a> { /// is the smallest number among them). fn med3(&mut self, a: V, b: V, third: V) -> V { let c = self.cur; + // Between two constants in order: the lower one for a NaN either way. + if host_rdna() & super::rdna::MED3 != 0 { + let k = [a, b, third].map(|x| self.s.m.float_k(x)); + let ordered = match k { + [None, Some(x), Some(y)] => Some((a, b, third, x, y)), + [Some(x), None, Some(y)] => Some((b, a, third, x, y)), + [Some(x), Some(y), None] => Some((third, a, b, x, y)), + _ => None, + }; + if let Some((v, p, q, x, y)) = ordered + && !x.is_nan() + && !y.is_nan() + && x != y + { + let (low, high) = if x < y { (p, q) } else { (q, p) }; + let t = self.binary(35, v, low); + return self.binary(36, t, high); + } + } let lo = self.binary(36, a, b); let hi = self.binary(35, a, b); let t = self.binary(36, hi, third); @@ -3829,6 +3875,9 @@ impl<'a> Lower<'a> { fn fract(&mut self, a: V, threshold: f32, below_one: f32) -> V { let c = self.cur; let r = self.unary(22, a); + if host_rdna() & super::rdna::FRACT != 0 && below_one == f32::from_bits(0x3F7F_FFFF) { + return r; + } let limit = self.s.m.f32(threshold.to_bits()); let k = self.s.m.f32(below_one.to_bits()); let over = self.s.m.cmp(c, pred::OGE, r, limit); @@ -3878,6 +3927,28 @@ impl<'a> Lower<'a> { /// `0 × anything = 0`, as in D3D9. fn legacy_mul(&mut self, a: V, b: V) -> V { let c = self.cur; + if host_rdna() & super::rdna::LEGACY != 0 { + let m = self.s.m.bin(c, Bin::Mul, a, b); + let zero = self.s.m.f32(0); + // A product is not 0 only where one factor is 0 and the other an + // infinity or no number: never of a value with itself, nor of two + // finite ones, and only where the finite one of two is 0. + let (fa, fb) = (self.s.m.bounded(a, 12).is_some(), self.s.m.bounded(b, 12).is_some()); + let not_zero = |l: &Self, x: V| l.s.m.float_k(x).is_some_and(|k| k != 0.0 && k.is_finite()); + if a == b || fa && fb || not_zero(self, a) || not_zero(self, b) { + return m; + } + let asked = match (fa, fb) { + (true, _) => a, + (_, true) => b, + _ => { + let (a, b) = (self.unary(6, a), self.unary(6, b)); + self.binary(36, a, b) + } + }; + let z = self.s.m.cmp(c, pred::OEQ, asked, zero); + return self.s.m.select(c, z, zero, m); + } let m = self.s.m.bin(c, Bin::Mul, a, b); let zero = self.s.m.f32(0); let az = self.s.m.cmp(c, pred::OEQ, a, zero); diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index f98517d..479d149 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -99,6 +99,8 @@ mod threading; #[cfg(windows)] pub mod validator; #[cfg(all(test, windows))] +mod probe_tests; +#[cfg(all(test, windows))] mod size_tests; #[cfg(all(test, windows))] mod valu_tests; @@ -114,7 +116,7 @@ use crate::{ShaderError, io, ir, resource, structure}; pub use bitcode::census; pub use sampler::StaticSampler; -pub use lower::{host_settings, set_host_max_wave}; +pub use lower::{host_settings, set_host_max_wave, set_host_rdna}; pub use rect::rect_list_gs; pub use shader::{ MEMORY_FAULTS, MEMORY_PAGES, MEMORY_READ_ONLY, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES, @@ -200,6 +202,57 @@ pub fn shader_opt() -> u32 { *PASSES.get_or_init(|| parse_shader_opt(std::env::var("VICTORY_SHADER_OPT").ok().as_deref())) } +/// On a host whose shaders run on the console's own kind of hardware (AMD +/// RDNA, [`set_host_rdna`]): which of the console's float instructions are +/// written as the one host operation the driver makes the same instruction +/// of, instead of spelled out in operations every host agrees on. +/// `VICTORY_RDNA_FLOAT`: a set of [`rdna`]'s bits (decimal or `0x` hex); all +/// of them when it is unset, `0` none. Nothing on other hosts. +/// +/// Measured on an RX 7900 XTX (a frame of the yard, replayed turn by turn with +/// and without): the title's dispatches and draws 18.4 -> 17.6 ms, 0.4 of it +/// without [`rdna::LEGACY`]. Tried and worth nothing there: `v_mad_f32` as one +/// multiply-add, a fast reciprocal, scalar buffer loads of four dwords at once, +/// a wave size for every compute program (32, 64, the console's). +/// +/// Part of the translation: the shader cache keys on it ([`host_settings`]). +pub fn rdna_float() -> u32 { + static BITS: std::sync::OnceLock = std::sync::OnceLock::new(); + *BITS.get_or_init(|| { + let value = std::env::var("VICTORY_RDNA_FLOAT").ok(); + parse_set(value.as_deref(), rdna::ALL, rdna::ALL) + }) +} + +/// The bits of [`rdna_float`]. +pub mod rdna { + /// `v_max_f32` and the like: the host's FMax and FMin, without the code + /// that orders -0 below +0. + pub const MAX_MIN: u32 = 1; + /// `v_mul_legacy_f32` and the like (0 times anything is 0): a plain product + /// where no factor can be an infinity or no number where the other is 0, + /// and one comparison where it can. A zero may have the other sign. + pub const LEGACY: u32 = 2; + /// `v_med3_f32` of a value between two ordered constants: a minimum of a + /// maximum. + pub const MED3: u32 = 4; + /// `v_fract_f32`: the host's Frc as it is. + pub const FRACT: u32 = 8; + pub const ALL: u32 = 15; +} + +/// A switch's set of bits; `unset` when it is unset or unreadable. Pure, for +/// testing. +fn parse_set(value: Option<&str>, unset: u32, all: u32) -> u32 { + let parsed = value + .map(str::trim) + .and_then(|v| match v.strip_prefix("0x") { + Some(hex) => u32::from_str_radix(hex, 16).ok(), + None => v.parse().ok(), + }); + parsed.map_or(unset, |n| n & all) +} + /// Everything a translation depends on besides the container: the /// translator's own source (hashed at build time), the value of every /// `VICTORY_*` switch it reads, the host facts the device hands it (widest @@ -220,6 +273,7 @@ pub fn translation_fingerprint() -> Vec { out.push(0); } out.extend_from_slice(&lower::host_max_wave().to_le_bytes()); + out.extend_from_slice(&lower::host_rdna().to_le_bytes()); out.extend_from_slice(&shader::view_heap_limit().to_le_bytes()); out.extend_from_slice(&shader::raw_views().to_le_bytes()); out.extend_from_slice(&loop_limit().to_le_bytes()); diff --git a/crates/victory-shader/src/emit/probe_tests.rs b/crates/victory-shader/src/emit/probe_tests.rs new file mode 100644 index 0000000..fd109ba --- /dev/null +++ b/crates/victory-shader/src/emit/probe_tests.rs @@ -0,0 +1,74 @@ +//! Not a test of the translator: what the host's compiler makes of DXIL. +//! `VICTORY_PROBE=` and `--ignored probe`: each `.dxil` there (a +//! compute program with a constant buffer `b0` of four dwords and a raw +//! buffer, slot 0 of the view heap) is run on the card. `sem*` programs are +//! given the bits of 0.0, infinity, -0.0 and a NaN and what they store is +//! printed; of the others the time is (several runs of 4096 groups). + +use super::HostShader; +use super::host::{Dispatch, Host, Root, View}; +use crate::native::{HwStage, RootType}; + +#[test] +#[ignore = "a tool: VICTORY_PROBE="] +fn probe() { + let Some(folder) = std::env::var_os("VICTORY_PROBE") else { return }; + let host = Host::new(false).expect("a card"); + let mut files: Vec<_> = std::fs::read_dir(folder) + .expect("the folder") + .filter_map(|e| Some(e.ok()?.path())) + .filter(|p| p.extension().is_some_and(|e| e == "dxil")) + .collect(); + files.sort(); + for file in files { + let name = file.file_stem().unwrap_or_default().to_string_lossy().into_owned(); + let shader = HostShader { + stage: HwStage::Cs, + dxil: std::fs::read(&file).expect("the file"), + user_data: (0..4) + .map(|n| super::UserData { index: n, slot: 0, root: RootType::Constants, dword: n }) + .collect(), + samplers: Vec::new(), + static_samplers: Vec::new(), + root_cbvs: Vec::new(), + root_srvs: Vec::new(), + root_uavs: Vec::new(), + root_indexed_views: Vec::new(), + }; + let (root, pso) = match host.compute_pipeline(&shader) { + Ok(made) => made, + Err(e) => { + println!("{name}: {e}"); + continue; + } + }; + let run = |constants: [u32; 4], groups: u32| { + let began = std::time::Instant::now(); + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(constants.to_vec()))], + views: &[View::RawUav(64)], + samplers: &[], + groups: [groups, 1, 1], + }, + ) + .expect("a dispatch"); + (out[0].clone(), began.elapsed().as_secs_f64() * 1e3) + }; + if name.starts_with("sem") { + let (out, _) = run([0, 0x7F80_0000, 0x8000_0000, 0x7FC0_0000], 1); + for (n, x) in out.iter().enumerate().take(40) { + println!("{name} {n:>2}: {x:08x} {}", f32::from_bits(*x)); + } + continue; + } + let constants = [0.37f32.to_bits(), 0.11f32.to_bits(), 16384, 0]; + run(constants, 64); + let mut times: Vec = (0..9).map(|_| run(constants, 4096).1).collect(); + times.sort_by(f64::total_cmp); + println!("{name}: {:.2} ms (least {:.2})", times[times.len() / 2], times[0]); + } +} diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index cd2806f..1062843 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -1912,3 +1912,88 @@ fn whole_wave_f64_sum_and_cvt_f32_f64() { } } } + +/// Whether the hardware adapter is an AMD RDNA card's: what the translator +/// writes for one ([`super::rdna`]) holds there. +fn rdna_card() -> bool { + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::*; + let Ok(host) = Host::new(false) else { return false }; + let mut waves = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default(); + // SAFETY: plain queries. + unsafe { + let amd = CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) + .and_then(|f| f.EnumAdapterByLuid::(host.device.GetAdapterLuid())) + .and_then(|a| a.GetDesc1()) + .is_ok_and(|d| d.VendorId == 0x1002); + amd && host + .device + .CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS1, + (&raw mut waves).cast(), + size_of_val(&waves) as u32, + ) + .is_ok() + && waves.WaveLaneCountMin == 32 + && waves.WaveLaneCountMax == 64 + } +} + +/// The forms written for the console's own kind of hardware give, on such a +/// card, what the ones spelled out for every host give; a legacy product's +/// zero may have the other sign. +#[test] +fn rdna_forms_give_what_the_spelled_out_ones_give() { + if !rdna_card() { + eprintln!("no RDNA card; skipped"); + return; + } + const ONE: u16 = 242; + const MINUS_ONE: u16 = 243; + let (a, b, c) = (vgpr(1), vgpr(2), vgpr(3)); + let saturated = vop3_mod(0x110, 5, vgpr(1), vgpr(1), 0, 0, 0, 0, true); + let two = |x: [u32; 2], y: [u32; 2]| [x, y].concat(); + let bodies: [(&str, Vec, bool); 14] = [ + ("max", vop3(0x110, 0, a, b, 0).to_vec(), true), + ("min", vop3(0x10F, 0, a, b, 0).to_vec(), true), + ("max3", vop3(0x154, 0, a, b, c).to_vec(), true), + ("min3", vop3(0x151, 0, a, b, c).to_vec(), true), + ("med3 0 1", vop3(0x157, 0, a, 128, ONE).to_vec(), true), + ("med3 1 0", vop3(0x157, 0, ONE, a, 128).to_vec(), true), + ("med3 1 -1", vop3(0x157, 0, ONE, MINUS_ONE, a).to_vec(), true), + ("fract", vec![vop1(0x020, 0, a)], true), + ("mul_legacy", vop3(0x107, 0, a, b, 0).to_vec(), false), + ("mul_legacy by itself", vop3(0x107, 0, a, a, 0).to_vec(), false), + ("mul_legacy by a constant", vop3(0x107, 0, a, MINUS_ONE, 0).to_vec(), false), + ("mul_legacy of a saturated", two(saturated, vop3(0x107, 0, vgpr(5), b, 0)), false), + ("mad_legacy", vop3(0x140, 0, a, b, c).to_vec(), false), + ("max of a mul_legacy", two(vop3(0x107, 5, a, b, 0), vop3(0x110, 0, vgpr(5), c, 0)), false), + ]; + let numbers = [0.0f32, -0.0, 1.0, -1.0, 0.3, -2.5e-7, 3e38, f32::INFINITY, f32::NEG_INFINITY, f32::NAN]; + let mut cases = Vec::new(); + for (i, x) in numbers.iter().enumerate() { + for (j, y) in numbers.iter().enumerate() { + let z = numbers[(3 * i + j) % numbers.len()]; + cases.push([x.to_bits(), y.to_bits(), z.to_bits(), 0]); + } + } + for (name, body, exact) in bodies { + let mut got: Vec> = Vec::new(); + let mut written = Vec::new(); + for bits in [0, super::rdna::ALL] { + lower::TEST_RDNA.set(Some(bits)); + let shader = build_valu_cs(&body); + lower::TEST_RDNA.set(None); + written.push(shader.dxil.clone()); + let mut all = Vec::new(); + run_cases_on(&shader, &cases, &[("hardware", false)], |_, _, _, r| all.push(r)); + got.push(all); + } + assert_ne!(written[0], written[1], "{name}: written alike"); + for (case, (&was, &is)) in cases.iter().zip(got[0].iter().zip(&got[1])) { + let (x, y) = (f32::from_bits(was), f32::from_bits(is)); + let same = was == is || x.is_nan() && y.is_nan() || !exact && x == 0.0 && y == 0.0; + assert!(same, "{name} of {:?}: {x} ({was:#x}), now {y} ({is:#x})", case.map(f32::from_bits)); + } + } +} From 4b3141fac5f019fc266fc0e2174a899b82007579 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 12:49:12 -0600 Subject: [PATCH 2/2] Frame replay: shaders of another translation (--retranslate, --shaders, --shaders-b turn by turn), times per pass as medians --shaders after local/models 098ec1d4. The capture's 1,266 containers are collected from the title's files once (beside the capture) and translated by this build in 15 s; a pipeline that is refused with them keeps the recorded ones. Co-Authored-By: Claude Opus 5.5 --- apps/victory/src/replay.rs | 84 ++++++++++++++ crates/victory-gpu/src/replay/play.rs | 156 +++++++++++++++++++++----- docs/replay.md | 2 + 3 files changed, 217 insertions(+), 25 deletions(-) diff --git a/apps/victory/src/replay.rs b/apps/victory/src/replay.rs index 490b523..38af935 100644 --- a/apps/victory/src/replay.rs +++ b/apps/victory/src/replay.rs @@ -195,6 +195,25 @@ pub(crate) struct Replay { /// `:` (repeatable). #[arg(long)] split: Vec, + /// Take shaders from this folder where it has them (`.dxil`, by the + /// hash the runtime names the title's shader by). + #[arg(long)] + shaders: Option, + /// With --compare: the folder the second run's shaders are from. + #[arg(long)] + shaders_b: Option, + /// Only translate the capture's shaders, into this folder (for --shaders), + /// with the translator's settings of this run. Containers are looked up in + /// `containers` beside the capture, and first collected there from the + /// title's files. + #[arg(long)] + retranslate: Option, + /// With --retranslate: the view heap's null slot, and where raw twins of + /// views start, as the capture's shaders have them (0: none). + #[arg(long, default_value_t = 0)] + view_limit: u32, + #[arg(long, default_value_t = 0)] + raw_views: u32, /// Use the D3D12 debug layer (slow). #[arg(long)] debug_layer: bool, @@ -229,6 +248,9 @@ pub(crate) fn run(r: Replay) -> Result<()> { let lists = range(text).with_context(|| format!("--flow {text}"))?; return play::look::flow(&r.folder, lists, r.flow_draws, r.flow_slots, &mut |line| println!("{line}")); } + if let Some(into) = &r.retranslate { + return retranslate(&r.folder, into, r.view_limit, r.raw_views); + } let until = match &r.until { Some(text) => Some( text.split_once(':') @@ -270,6 +292,8 @@ pub(crate) fn run(r: Replay) -> Result<()> { only, until, skip_shaders: r.skip_shader, + shaders: r.shaders, + shaders_b: r.shaders_b, compare: r.compare, debug: r.debug_layer, breadcrumbs: r.breadcrumbs, @@ -409,6 +433,66 @@ pub(crate) fn run(r: Replay) -> Result<()> { Ok(()) } +/// Translates the capture's shaders into `into`. +fn retranslate(folder: &std::path::Path, into: &std::path::Path, view_limit: u32, raw_views: u32) -> Result<()> { + use std::sync::atomic::{AtomicUsize, Ordering}; + let wanted = play::title_shaders(folder)?; + let kept = play::find(folder)?.with_file_name("containers"); + std::fs::create_dir_all(&kept)?; + std::fs::create_dir_all(into)?; + let mut missing: std::collections::HashSet<&str> = wanted + .iter() + .map(|w| w.1.as_str()) + .filter(|h| !kept.join(format!("{h}.cdxil")).exists()) + .collect(); + if !missing.is_empty() { + println!("{} of {} containers are looked for in the title's files", missing.len(), wanted.len()); + for root in crate::default_paths(Vec::new())? { + for entry in walkdir::WalkDir::new(root).into_iter().filter_map(std::result::Result::ok) { + let size = entry.metadata().map_or(0, |m| m.len()); + if missing.is_empty() || !entry.file_type().is_file() || size > crate::shader::MAX_FILE { + continue; + } + let Ok(data) = std::fs::read(entry.path()) else { continue }; + for source in crate::shader::sources(&data) { + let Some(bytes) = source.bytes() else { continue }; + let hash = blake3::hash(&bytes).to_hex()[..16].to_owned(); + if missing.remove(hash.as_str()) { + std::fs::write(kept.join(format!("{hash}.cdxil")), &bytes[..])?; + } + } + } + } + } + println!("{} containers not found", missing.len()); + victory_shader::emit::set_host_max_wave(64); + victory_shader::emit::set_host_rdna(true); + victory_shader::emit::set_view_heap_limit(view_limit); + victory_shader::emit::set_raw_views(raw_views); + let all: Vec<_> = wanted.iter().collect(); + let (next, done) = (AtomicUsize::new(0), AtomicUsize::new(0)); + let started = std::time::Instant::now(); + std::thread::scope(|s| { + for _ in 0..std::thread::available_parallelism().map_or(4, |n| n.get()) { + s.spawn(|| { + while let Some((stage, hash)) = all.get(next.fetch_add(1, Ordering::Relaxed)) { + let Ok(bytes) = std::fs::read(kept.join(format!("{hash}.cdxil"))) else { continue }; + match victory_shader::emit::translate(&bytes) { + Ok(t) => { + if std::fs::write(into.join(format!("{hash}.dxil")), &t.dxil).is_ok() { + done.fetch_add(1, Ordering::Relaxed); + } + } + Err(e) => println!("{stage} {hash}: {e}"), + } + } + }); + } + }); + println!("{} of {} shaders translated, {:.1} s", done.into_inner(), all.len(), started.elapsed().as_secs_f64()); + Ok(()) +} + #[cfg(test)] mod tests { #[test] diff --git a/crates/victory-gpu/src/replay/play.rs b/crates/victory-gpu/src/replay/play.rs index b823576..fa55c85 100644 --- a/crates/victory-gpu/src/replay/play.rs +++ b/crates/victory-gpu/src/replay/play.rs @@ -96,6 +96,11 @@ pub struct Options { /// Skip what runs a pipeline whose name or shader hash has one of /// these in it. pub skip_shaders: Vec, + /// Shaders taken from this folder where it has them: `.dxil`, by + /// the hash the runtime names the title's shader by. + pub shaders: Option, + /// With `compare`: the folder the shaders of the second are from. + pub shaders_b: Option, /// Run the frame unchanged first, and compare. pub compare: bool, /// The debug layer, if it is installed. @@ -129,6 +134,8 @@ impl Default for Options { only: None, until: None, skip_shaders: Vec::new(), + shaders: None, + shaders_b: None, compare: false, debug: false, breadcrumbs: false, @@ -180,7 +187,7 @@ pub struct Report { pub delta_ms: Vec, /// Of the last loop, by submission: lists, ms. pub submits: Vec<(usize, f64)>, - /// With detailed timing, of the last loop: ms and count by category. + /// With detailed timing: ms (median of the loops) and count by category. pub categories: Vec<(String, f64, u32)>, /// With detailed timing: ms, count and name of the costliest pipelines. pub shaders: Vec<(f64, u32, String)>, @@ -326,6 +333,43 @@ pub fn find(folder: &Path) -> Result { .ok_or_else(|| anyhow!("no capture (frame.bin) in {}", folder.display())) } +/// The stage and hash by which the runtime names each of the title's shaders +/// in a capture. +pub fn title_shaders(folder: &Path) -> Result> { + let frame = Frame::read(&find(folder)?.join("frame.bin"))?; + let mut all = std::collections::BTreeSet::new(); + for p in &frame.pipelines { + for part in &p.parts { + if let wire::Part::Code { blob, .. } = part + && let Some(hash) = title_hash(p, *blob) + { + let at = p.name.find(hash).unwrap_or(0); + let stage = p.name[..at].trim_end().rsplit(['[', ' ']).next().unwrap_or(""); + all.insert((stage.to_owned(), hash.to_owned())); + } + } + } + Ok(all) +} + +/// The hash by which the runtime names the title's shader that code blob +/// `blob` of pipeline `p` is the translation of. +fn title_hash(p: &wire::Pipeline, blob: u32) -> Option<&str> { + let kind = p.parts.iter().find_map(|part| match part { + wire::Part::Code { kind, blob: b } if *b == blob => Some(*kind), + _ => None, + })?; + let stage = match D3D12_PIPELINE_STATE_SUBOBJECT_TYPE(kind) { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS => "vertex ", + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS => "pixel ", + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS => "mesh ", + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS => "compute ", + _ => return None, + }; + let at = p.name.find(stage)? + stage.len(); + p.name.get(at..at + 16) +} + /// Writes the DXIL of the pipelines whose name has `text` in it to `shaders` /// in the capture, and the pipelines' descriptions; what was written. pub fn dump(folder: &Path, text: &str) -> Result> { @@ -411,7 +455,7 @@ pub fn listing(folder: &Path, lists: (u32, u32), line: &mut dyn FnMut(&str)) -> pub fn replay(folder: &Path, options: &Options) -> Result> { let mut player = Player::load(folder, options)?; let mut out = Vec::new(); - if options.compare && options.edited() { + if options.compare && (options.edited() || options.shaders_b.is_some()) { // Turn by turn: what else the machine does falls on both. let image = Some(player.folder.join("replay-unchanged.png")); let plain = Options { @@ -419,11 +463,20 @@ pub fn replay(folder: &Path, options: &Options) -> Result> ..options.plain() }; let mut a = player.prepare(&plain)?; + // The lists of the first hold its pipelines by name alone: kept. + let _pipelines = match &options.shaders_b { + Some(folder) => { + let kept = std::mem::take(&mut player.pipelines); + player.make_pipelines(Some(folder))?; + kept + } + None => HashMap::new(), + }; let mut b = player.prepare(options)?; let (mut stamps_a, mut stamps_b) = (Vec::new(), Vec::new()); for _ in 0..options.loops.max(1) { - stamps_a = player.once(&plain, &mut a)?; - stamps_b = player.once(options, &mut b)?; + stamps_a.push(player.once(&plain, &mut a)?); + stamps_b.push(player.once(options, &mut b)?); } out.push(("unchanged".into(), player.finish(&plain, a, &stamps_a)?)); out.push(("with the experiments".into(), player.finish(options, b, &stamps_b)?)); @@ -580,7 +633,7 @@ impl Player { let mut at = Instant::now(); player.make_resources(options.buffers, &options.only_buffers)?; step("resources", &mut at); - player.make_pipelines()?; + player.make_pipelines(options.shaders.as_deref())?; step("pipelines", &mut at); player.make_descriptors()?; step("descriptors", &mut at); @@ -828,14 +881,21 @@ impl Player { Ok(()) } - fn make_pipelines(&mut self) -> Result<()> { + fn make_pipelines(&mut self, shaders: Option<&Path>) -> Result<()> { for (id, blob) in &self.frame.roots { + if self.roots.contains_key(id) { + // (Made for another set of shaders: the root signatures are the same.) + continue; + } // SAFETY: a blob the host took. let root = unsafe { self.device.CreateRootSignature(0, &blob.0) } .with_context(|| format!("root signature {id}"))?; self.roots.insert(*id, root); } for s in &self.frame.signatures { + if self.signatures.contains_key(&s.id) { + continue; + } let desc = D3D12_COMMAND_SIGNATURE_DESC { ByteStride: s.stride, NumArgumentDescs: s.args.len() as u32, @@ -851,6 +911,9 @@ impl Player { self.signatures.extend(made.map(|m| (s.id, m))); } for q in &self.frame.query_heaps { + if self.queries.contains_key(&q.id) { + continue; + } let desc = D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE(q.kind), Count: q.count, @@ -870,18 +933,34 @@ impl Player { .map_or(4, |n| n.get() / 2) .max(1); let (frame, roots) = (&self.frame, &self.roots); + let (swapped, kept) = (AtomicUsize::new(0), AtomicUsize::new(0)); std::thread::scope(|scope| { for _ in 0..threads { scope.spawn(|| { while let Some(p) = frame.pipelines.get(next.fetch_add(1, Ordering::Relaxed)) { - let code = |i: u32| { + let recorded = |i: u32| { let c = frame.codes.get(i as usize)?; let mut bytes = vec![0; c.len as usize]; read_at(&file, &mut bytes, c.at).ok()?; Some(bytes) }; - let m = - super::pso::make(&device, &p.parts, |id| roots.get(&id).cloned(), code); + let root = |id: u32| roots.get(&id).cloned(); + let taken = std::cell::Cell::new(false); + let mut m = super::pso::make(&device, &p.parts, root, |i| { + let other = shaders.and_then(|dir| { + let hash = title_hash(p, i)?; + std::fs::read(dir.join(format!("{hash}.dxil"))).ok() + }); + taken.set(taken.get() || other.is_some()); + other.or_else(|| recorded(i)) + }); + if taken.get() && m.is_err() { + // Not for the root signature or the other stage recorded. + kept.fetch_add(1, Ordering::Relaxed); + m = super::pso::make(&device, &p.parts, root, recorded); + } else if taken.get() { + swapped.fetch_add(1, Ordering::Relaxed); + } made.lock() .unwrap_or_else(|e| e.into_inner()) .push((p.id, m)); @@ -896,6 +975,15 @@ impl Player { Err(e) => refused.push((id, e)), } } + if shaders.is_some() { + let n = format!( + "{} of {} pipelines made with shaders of the folder given, {} refused with them (as recorded)", + swapped.into_inner(), + self.frame.pipelines.len(), + kept.into_inner() + ); + self.note(n); + } if let Some((id, e)) = refused.first() { let n = format!( "{} pipelines could not be made again, first {}: {e}", @@ -2974,7 +3062,7 @@ impl Player { let _awake = if o.awake { crate::host::awake::start(&self.device, || true) } else { None }; let mut stamps = Vec::new(); for _ in 0..o.loops.max(1) { - stamps = self.once(o, &mut made)?; + stamps.push(self.once(o, &mut made)?); } self.finish(o, made, &stamps) } @@ -3034,7 +3122,7 @@ impl Player { } /// The report after the last run. - fn finish(&mut self, o: &Options, (built, mut report): (Sends, Report), stamps: &[u64]) -> Result { + fn finish(&mut self, o: &Options, (built, mut report): (Sends, Report), stamps: &[Vec]) -> Result { if o.detailed { self.detail(&built, stamps, o, &mut report); } @@ -3049,23 +3137,41 @@ impl Player { Ok(report) } - /// The last loop's time by command. - fn detail(&self, built: &Sends, stamps: &[u64], o: &Options, report: &mut Report) { - let mut kinds: BTreeMap<&str, (f64, u32)> = BTreeMap::new(); - let mut shaders: HashMap = HashMap::new(); - for l in built.steps.iter().flat_map(|(_, l)| l) { - let mut before = stamps[l.first as usize]; - for &(at, kind, pso) in &l.stamps { - let ms = stamps[at].saturating_sub(before) as f64 * 1e3 / self.frequency; - before = before.max(stamps[at]); - let k = kinds.entry(kind).or_default(); - *k = (k.0 + ms, k.1 + 1); - if pso != NONE { - let s = shaders.entry(pso).or_default(); - *s = (s.0 + ms, s.1 + 1); + /// The time by command: the median of the loops, without the first (which + /// is slower) where there are others. + fn detail(&self, built: &Sends, stamps: &[Vec], o: &Options, report: &mut Report) { + let mut kinds: BTreeMap<&str, (Vec, u32)> = BTreeMap::new(); + let mut shaders: HashMap, u32)> = HashMap::new(); + let loops = if stamps.len() > 2 { &stamps[1..] } else { stamps }; + for stamps in loops { + let mut of_kind: BTreeMap<&str, (f64, u32)> = BTreeMap::new(); + let mut of_shader: HashMap = HashMap::new(); + for l in built.steps.iter().flat_map(|(_, l)| l) { + let mut before = stamps[l.first as usize]; + for &(at, kind, pso) in &l.stamps { + let ms = stamps[at].saturating_sub(before) as f64 * 1e3 / self.frequency; + before = before.max(stamps[at]); + let k = of_kind.entry(kind).or_default(); + *k = (k.0 + ms, k.1 + 1); + if pso != NONE { + let s = of_shader.entry(pso).or_default(); + *s = (s.0 + ms, s.1 + 1); + } } } + for (k, (ms, n)) in of_kind { + let all = kinds.entry(k).or_default(); + all.0.push(ms); + all.1 = n; + } + for (k, (ms, n)) in of_shader { + let all = shaders.entry(k).or_default(); + all.0.push(ms); + all.1 = n; + } } + let kinds = kinds.into_iter().map(|(k, (ms, n))| (k, (median(&ms), n))); + let shaders = shaders.into_iter().map(|(k, (ms, n))| (k, (median(&ms), n))); report.categories = kinds .into_iter() .map(|(k, (ms, n))| (k.to_owned(), ms, n)) diff --git a/docs/replay.md b/docs/replay.md index 0459d7d..8dcd7e6 100644 --- a/docs/replay.md +++ b/docs/replay.md @@ -69,6 +69,8 @@ with the presented one. | `--only 3..7` | runs these lists; of the others only barriers | | `--no-merge` | copies of what the CPU wrote also overwrite the card's own results (below) | | `--skip-shader ` | leaves out what runs pipelines with the text in their name or DXIL hash (repeatable) | +| `--shaders ` | takes shaders from the folder where it has them: `.dxil`, by the hash the runtime names the title's shader by; with `--compare --shaders-b ` a second set, turn by turn with the first | +| `--retranslate ` | only writes that folder: the capture's shaders translated by this build with the `VICTORY_*` switches of this run (`--view-limit`, `--raw-views`: the view heap's null slot and where raw views start, as the capture's shaders have them) | | `--no-restore` | leaves what a loop changed, and makes no copies to restore from (of a capture that does not fit in the card's memory with them) | | `--pace ` | a wait after each submission sent: the card stands idle between them, as in a game that prepares the next one | | `--awake` | keeps the card's clocks up (`VICTORY_CARD_AWAKE=1`) |