diff --git a/README.md b/README.md index 9c047fd54..2b96962b1 100644 --- a/README.md +++ b/README.md @@ -157,6 +157,21 @@ environment variables pointing at your own files – `XCL_SAMPLE_RPF` (shader pa tests pass without running anything (`scripts/test.ps1` lists the ones not set). No game data is part of the repository. +**Shader compile time** without game data: `crates/xcl/tests/compile_bench` generates RDNA2 +programs (seeded; knobs for size, divergent branches, loops, wave size, LDS, memory, buffer and +image accesses) and times their HLSL → DXIL compile. Every test run compiles a small set; +`scripts/compile_bench.ps1` runs the full one (or `-Set large`, only the multi-megabyte programs) +in release and writes JSON / CSV and a log that ranks the programs by DXC time (median, p90 and +maximum of the set), and +`scripts/compile_bench_compare.py` compares two runs program by program (any size change, and +time changes beyond the run-to-run noise, 5 % unless `--noise` says otherwise; e.g. `main` and a +branch, on the same machine): + +```powershell +.\scripts\compile_bench.ps1 # -> target\compile_bench\\compile_bench.json +python -I scripts/compile_bench_compare.py \compile_bench.json \compile_bench.json +``` + ## Licenses **GPL-2.0-only** (`LICENSE`); third-party sources: `THIRD_PARTY.md` (including AMD's diff --git a/crates/xcl/tests/compile_bench/gen.rs b/crates/xcl/tests/compile_bench/gen.rs new file mode 100644 index 000000000..5a2dbdeb5 --- /dev/null +++ b/crates/xcl/tests/compile_bench/gen.rs @@ -0,0 +1,217 @@ +//! Generated RDNA2 programs for compile-time measurements: no game data, the same program for +//! the same knobs and seed. The code is meant to be translated and compiled, not run: register +//! values and addresses are not set up to compute anything. +//! +//! Register use: v0 is the lane id (read only), v1 the lane's byte offset for memory, v2.. the +//! `vgprs` pool. s[2:3] is the memory base, s4.. the `sgprs` pool, s[32:35] the buffer's V#, +//! s[40:47] the image's T#, s[48:51] its S#, s[64 + 2d] the EXEC saved by an `if` at depth d, +//! s[80 + d] the counter of a loop at depth d. + +use xcl::gpu::rdna2::encode; +use xcl::gpu::recomp::{CsInterface, Mode, Options}; + +#[derive(Debug, Clone, PartialEq, serde::Serialize)] +pub struct Knobs { + pub seed: u64, + /// operations (ALU and memory instructions); the control flow comes on top + pub ops: usize, + /// how deep divergent `if`s (v_cmp → s_and_saveexec → s_cbranch_execz) nest; 0: none + pub if_depth: u32, + /// percent of operation slots that open an `if` while `if_depth` allows one + pub divergent_pct: u32, + /// uniform loops (counter in an SGPR, backward s_cbranch_scc1), each `loop_depth` deep + pub loops: u32, + pub loop_depth: u32, + /// trips of every loop, 1..=64 (an inline constant) + pub loop_trips: u32, + /// wave64 (64-bit EXEC) or wave32 program + pub wave64: bool, + /// VGPRs the operations use, 2..=254; SGPRs, 1..=16 + pub vgprs: u32, + pub sgprs: u32, + /// percent of operations that are LDS reads / writes, and global or scalar memory accesses + pub lds_pct: u32, + pub mem_pct: u32, + /// percent of operations that are buffer loads / stores (V#), and image loads / samples (T#) + pub buffer_pct: u32, + pub image_pct: u32, + /// translate as a compute shader (64 threads, 4 user SGPRs) instead of a kernel + pub compute: bool, +} + +impl Default for Knobs { + fn default() -> Self { + Knobs { + seed: 1, ops: 200, if_depth: 2, divergent_pct: 10, loops: 0, loop_depth: 1, loop_trips: 4, wave64: true, vgprs: 16, sgprs: 8, + lds_pct: 5, mem_pct: 10, buffer_pct: 0, image_pct: 0, compute: false, + } + } +} + +impl Knobs { + /// The recompiler options the program is meant for: kernel or compute mode, its wave size. + pub fn options(&self) -> Options { + let mode = if self.compute { + Mode::Compute(CsInterface { threads: [64, 1, 1], user_sgprs: 4, tid_components: 1, ..CsInterface::default() }) + } else { + Mode::Kernel + }; + Options { mode, wave64: self.wave64, ..Options::default() } + } +} + +const VCC: u64 = 106; +const EXEC: u64 = 126; +const LIT: u64 = 255; +const V: u64 = 256; + +fn inst(name: &str, enc: &str, fields: &[(&str, u64)], lit: Option) -> Vec { + encode(name, enc, fields, lit).unwrap_or_else(|e| panic!("{name}: {e}")) +} + +/// splitmix64: small, and the same sequence on every platform +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + + fn below(&mut self, n: u64) -> u64 { + self.next() % n + } +} + +struct Gen<'a> { + k: &'a Knobs, + rng: Rng, +} + +impl Gen<'_> { + fn vgpr(&mut self) -> u64 { + 2 + self.rng.below(self.k.vgprs as u64) + } + + fn sgpr(&mut self) -> u64 { + 4 + self.rng.below(self.k.sgprs as u64) + } + + fn op(&mut self) -> Vec { + let r = self.rng.below(100) as u32; + if r < self.k.mem_pct { + return match self.rng.below(3) { + 0 => inst("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", self.vgpr()), ("ADDR", 1), ("SADDR", 2), ("OFFSET", 4 * self.rng.below(256))], None), + 1 => inst("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 1), ("DATA", self.vgpr()), ("SADDR", 2), ("OFFSET", 4 * self.rng.below(256))], None), + _ => inst("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", self.sgpr()), ("SBASE", 1), ("OFFSET", 4 * self.rng.below(256))], None), + }; + } + if r < self.k.mem_pct + self.k.lds_pct { + return if self.rng.below(2) == 0 { + inst("DS_WRITE_B32", "ENC_DS", &[("ADDR", 1), ("DATA0", self.vgpr())], None) + } else { + inst("DS_READ_B32", "ENC_DS", &[("VDST", self.vgpr()), ("ADDR", 1)], None) + }; + } + let resources = self.k.mem_pct + self.k.lds_pct + self.k.buffer_pct; + if r < resources { + let name = if self.rng.below(2) == 0 { "BUFFER_LOAD_DWORD" } else { "BUFFER_STORE_DWORD" }; + return inst(name, "ENC_MUBUF", &[("VDATA", self.vgpr()), ("VADDR", 1), ("SRSRC", 8), ("SOFFSET", 128), ("OFFSET", 4 * self.rng.below(256)), ("OFFEN", 1)], None); + } + if r < resources + self.k.image_pct { + // 2D at (v0, v1), one channel + return if self.rng.below(2) == 0 { + inst("IMAGE_LOAD", "ENC_MIMG", &[("VDATA", self.vgpr()), ("VADDR", 0), ("SRSRC", 10), ("DMASK", 1), ("DIM", 1), ("UNORM", 1)], None) + } else { + inst("IMAGE_SAMPLE_LZ", "ENC_MIMG", &[("VDATA", self.vgpr()), ("VADDR", 0), ("SRSRC", 10), ("SSAMP", 12), ("DMASK", 1), ("DIM", 1)], None) + }; + } + // the rest: about one scalar operation for three vector ones, as in console programs + if self.rng.below(4) == 0 { + let name = ["S_ADD_U32", "S_XOR_B32", "S_MUL_I32"][self.rng.below(3) as usize]; + return inst(name, "ENC_SOP2", &[("SDST", self.sgpr()), ("SSRC0", self.sgpr()), ("SSRC1", self.sgpr())], None); + } + let (d, a, b, c) = (self.vgpr(), self.vgpr(), self.vgpr(), self.vgpr()); + match self.rng.below(6) { + 0 => inst("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", d), ("SRC0", V + a), ("VSRC1", b)], None), + 1 => inst("V_XOR_B32", "ENC_VOP2", &[("VDST", d), ("SRC0", self.sgpr()), ("VSRC1", b)], None), + 2 => inst("V_MUL_F32", "ENC_VOP2", &[("VDST", d), ("SRC0", LIT), ("VSRC1", b)], Some(0x3F80_0000 + (self.rng.below(1 << 16) as u32))), + 3 => inst("V_FMAC_F32", "ENC_VOP2", &[("VDST", d), ("SRC0", V + a), ("VSRC1", b)], None), + 4 => inst("V_MUL_LO_U32", "ENC_VOP3", &[("VDST", d), ("SRC0", V + a), ("SRC1", V + b)], None), + _ => inst("V_FMA_F32", "ENC_VOP3", &[("VDST", d), ("SRC0", V + a), ("SRC1", V + b), ("SRC2", V + c)], None), + } + } + + /// `n` operations, some of them inside divergent `if`s from depth `depth` on. + fn seq(&mut self, mut n: usize, depth: u32) -> Vec { + let mut v = Vec::new(); + while n > 0 { + if depth < self.k.if_depth && (self.rng.below(100) as u32) < self.k.divergent_pct { + let inner = n.min(4 + self.rng.below(12) as usize); + v.extend(self.divergent_if(inner, depth)); + n -= inner; + } else { + v.extend(self.op()); + n -= 1; + } + } + v + } + + fn divergent_if(&mut self, n: usize, depth: u32) -> Vec { + let save = 64 + 2 * depth as u64; + let (and_saveexec, or) = if self.k.wave64 { ("S_AND_SAVEEXEC_B64", "S_OR_B64") } else { ("S_AND_SAVEEXEC_B32", "S_OR_B32") }; + let body = self.seq(n, depth + 1); + let mut v = inst("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", LIT), ("VSRC1", self.vgpr())], Some(self.rng.next() as u32)); + v.extend(inst(and_saveexec, "ENC_SOP1", &[("SDST", save), ("SSRC0", VCC)], None)); + v.extend(inst("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", (body.len() / 4) as u64)], None)); + v.extend(body); + v.extend(inst(or, "ENC_SOP2", &[("SDST", EXEC), ("SSRC0", EXEC), ("SSRC1", save)], None)); + v + } + + /// A loop `levels` deep: each level runs `per_level` operations, then the next level. + fn nested_loop(&mut self, levels: u32, per_level: usize, depth: u32) -> Vec { + let counter = 80 + depth as u64; + let mut v = inst("S_MOV_B32", "ENC_SOP1", &[("SDST", counter), ("SSRC0", 128 + self.k.loop_trips as u64)], None); + let head = v.len(); + v.extend(self.seq(per_level, 0)); + if levels > 1 { + v.extend(self.nested_loop(levels - 1, per_level, depth + 1)); + } + v.extend(inst("S_SUB_U32", "ENC_SOP2", &[("SDST", counter), ("SSRC0", counter), ("SSRC1", 129)], None)); + v.extend(inst("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", counter), ("SSRC1", 128)], None)); + // the offset counts dwords from the instruction after the branch + let back = -(((v.len() - head) / 4 + 1) as i64); + let back = i16::try_from(back).expect("loop body exceeds SOPP branch range"); + v.extend(inst("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", back as u16 as u64)], None)); + v + } +} + +/// The program for `k`, ending in s_endpgm. Half of the operations go into the loops when +/// there are any, spread evenly over their levels; the rest runs before, between and after them. +pub fn program(k: &Knobs) -> Vec { + assert!((2..=254).contains(&k.vgprs) && (1..=16).contains(&k.sgprs), "{k:?}"); + assert!((1..=64).contains(&k.loop_trips) && k.loop_depth >= 1 && k.if_depth <= 8 && k.loop_depth <= 8, "{k:?}"); + assert!(k.lds_pct + k.mem_pct + k.buffer_pct + k.image_pct <= 100 && k.divergent_pct <= 100, "{k:?}"); + let mut g = Gen { k, rng: Rng(k.seed) }; + let mut v = inst("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 130), ("VSRC1", 0)], None); // v1 = lane * 4 + let (loops, levels) = (k.loops as usize, k.loop_depth as usize); + // every loop level runs at least one operation, so the program would get more than `ops` + assert!(k.ops / 2 >= loops * levels, "too few operations: ops {} for {loops} loops × {levels} levels needs ops ≥ {}", k.ops, 2 * loops * levels); + let per_level = (k.ops / 2).checked_div(loops * levels).unwrap_or(0); + let outside = k.ops.saturating_sub(per_level * levels * loops); + for i in 0..=loops { + // the operations outside the loops, split into loops + 1 runs + v.extend(g.seq(outside * (i + 1) / (loops + 1) - outside * i / (loops + 1), 0)); + if i < loops { + v.extend(g.nested_loop(k.loop_depth, per_level, 0)); + } + } + v.extend(inst("S_ENDPGM", "ENC_SOPP", &[], None)); + v +} diff --git a/crates/xcl/tests/compile_bench/main.rs b/crates/xcl/tests/compile_bench/main.rs new file mode 100644 index 000000000..d34fe6581 --- /dev/null +++ b/crates/xcl/tests/compile_bench/main.rs @@ -0,0 +1,352 @@ +//! Compile-time benchmark on generated RDNA2 programs (issue #1269): no game data, so it can +//! run anywhere, CI included. The generator is checked first: what each knob does is counted +//! in the disassembly of the program, and every program the knobs allow translates completely. +//! Then the programs are compiled with DXC and measured (`measure.rs`: what to set for the full +//! set and for the JSON / CSV output). + +mod gen; +mod measure; + +use gen::{program, Knobs}; +use xcl::gpu::rdna2::{disassemble, Line}; +use xcl::gpu::recomp::{dxc, runner, translate, Options}; + +fn mnemonic(l: &Line) -> &str { + l.text.split_whitespace().next().unwrap_or("") +} + +fn lines(code: &[u8]) -> Vec { + let ls = disassemble(code, 0, true); + assert!(ls.iter().all(|l| l.ok), "undecoded: {:?}", ls.iter().find(|l| !l.ok).map(|l| &l.text)); + assert_eq!(ls.iter().map(|l| l.bytes.len()).sum::(), code.len(), "the disassembly ends before the code"); + ls +} + +/// Target of a SOPP branch: SIMM16 dwords from the next instruction. +fn target(l: &Line) -> u64 { + let simm = u16::from_le_bytes([l.bytes[0], l.bytes[1]]) as i16 as i64; + (l.pc as i64 + 4 + 4 * simm) as u64 +} + +/// Instructions that the control flow and the prologue add (the rest are the operations). +const CONTROL: &[&str] = &[ + "v_lshlrev_b32", "v_cmp_gt_u32", "s_and_saveexec_b64", "s_and_saveexec_b32", "s_cbranch_execz", "s_or_b64", "s_or_b32", + "s_mov_b32", "s_sub_u32", "s_cmp_lg_u32", "s_cbranch_scc1", "s_endpgm", +]; + +#[derive(Debug, Default)] +struct Shape { + ops: usize, + ifs: usize, + if_depth: u32, + loops: usize, + loop_depth: u32, + lds: usize, + mem: usize, + buffer: usize, + image: usize, + max_vgpr: u32, +} + +fn shape(code: &[u8]) -> Shape { + let ls = lines(code); + let at = |pc: u64| ls.iter().position(|l| l.pc == pc).unwrap_or_else(|| panic!("no instruction at {pc:#x}")); + let mut s = Shape::default(); + let mut depth = 0u32; + let mut loops = Vec::new(); + for (i, l) in ls.iter().enumerate() { + let m = mnemonic(l); + match m { + "s_and_saveexec_b64" | "s_and_saveexec_b32" => { + s.ifs += 1; + depth += 1; + s.if_depth = s.if_depth.max(depth); + } + "s_or_b64" | "s_or_b32" => depth -= 1, + // an if's skip lands on its EXEC restore + "s_cbranch_execz" => assert!(mnemonic(&ls[at(target(l))]).starts_with("s_or_b"), "execz at {:#x}", l.pc), + // a loop's branch goes back to the instruction after its counter is set + "s_cbranch_scc1" => { + let head = at(target(l)); + assert!(head < i && mnemonic(&ls[head - 1]) == "s_mov_b32", "scc1 at {:#x}", l.pc); + loops.push((ls[head].pc, l.pc)); + } + _ => {} + } + if !CONTROL.contains(&m) { + s.ops += 1; + s.lds += m.starts_with("ds_") as usize; + s.mem += (m.starts_with("global_") || m.starts_with("s_load")) as usize; + s.buffer += m.starts_with("buffer_") as usize; + s.image += m.starts_with("image_") as usize; + } + for tok in l.text.split(|c: char| !c.is_ascii_alphanumeric()) { + if let Some(n) = tok.strip_prefix('v').and_then(|n| n.parse::().ok()) { + s.max_vgpr = s.max_vgpr.max(n); + } + } + } + assert_eq!(depth, 0, "every if restores EXEC"); + s.loops = loops.len(); + s.loop_depth = loops.iter().map(|&(h, b)| loops.iter().filter(|&&(h2, b2)| h2 <= h && b <= b2).count() as u32).max().unwrap_or(0); + s +} + +#[test] +fn same_knobs_and_seed_give_the_same_program() { + let k = Knobs { ops: 500, loops: 2, loop_depth: 2, ..Knobs::default() }; + assert_eq!(program(&k), program(&k)); + assert_ne!(program(&k), program(&Knobs { seed: 2, ..k })); +} + +#[test] +fn operations_and_control_flow_follow_the_knobs() { + for (ops, if_depth, loops, loop_depth) in [(200, 0, 0, 1), (400, 1, 1, 1), (600, 3, 2, 2), (2000, 8, 3, 4), (120, 2, 5, 3), (12, 0, 2, 3)] { + let k = Knobs { ops, if_depth, loops, loop_depth, divergent_pct: 30, ..Knobs::default() }; + let s = shape(&program(&k)); + assert_eq!(s.ops, ops, "{k:?}"); + assert!(s.if_depth <= if_depth && (if_depth == 0) == (s.ifs == 0), "{k:?}: {s:?}"); + assert_eq!((s.loops, s.loop_depth), ((loops * loop_depth) as usize, if loops > 0 { loop_depth } else { 0 }), "{k:?}"); + } + // always divergent: the ifs nest as deep as allowed + for if_depth in [1, 4, 8] { + let s = shape(&program(&Knobs { ops: 1000, if_depth, divergent_pct: 100, ..Knobs::default() })); + assert_eq!(s.if_depth, if_depth); + } + let none = shape(&program(&Knobs { ops: 1000, divergent_pct: 0, ..Knobs::default() })); + assert_eq!(none.ifs, 0); +} + +#[test] +#[should_panic(expected = "too few operations")] +fn knobs_with_fewer_operations_than_loop_levels_are_refused() { + // 2 × 3 levels need 12 operations: the program would get more than the 10 asked for + program(&Knobs { ops: 10, loops: 2, loop_depth: 3, ..Knobs::default() }); +} + +#[test] +fn wave_size_picks_the_exec_instructions() { + for wave64 in [true, false] { + let code = program(&Knobs { ops: 500, if_depth: 3, divergent_pct: 50, wave64, ..Knobs::default() }); + let ms: Vec = lines(&code).iter().map(|l| mnemonic(l).to_string()).collect(); + let (want, other) = if wave64 { ("_b64", "_b32") } else { ("_b32", "_b64") }; + assert!(ms.iter().any(|m| *m == format!("s_and_saveexec{want}"))); + assert!(!ms.iter().any(|m| *m == format!("s_and_saveexec{other}") || *m == format!("s_or{other}")), "wave64 {wave64}"); + } +} + +#[test] +#[should_panic(expected = "loop body exceeds SOPP branch range")] +fn oversized_loop_branches_are_refused() { + program(&Knobs { ops: 100_000, loops: 1, if_depth: 0, lds_pct: 0, mem_pct: 0, ..Knobs::default() }); +} + +#[test] +fn large_representable_loop_still_targets_its_body() { + let s = shape(&program(&Knobs { ops: 10_000, loops: 1, if_depth: 0, lds_pct: 0, mem_pct: 0, ..Knobs::default() })); + assert_eq!((s.ops, s.loops, s.loop_depth), (10_000, 1, 1)); +} + +#[test] +fn lds_and_memory_shares_follow_the_knobs() { + let at = |lds_pct, mem_pct| shape(&program(&Knobs { ops: 2000, lds_pct, mem_pct, ..Knobs::default() })); + let s = at(0, 0); + assert_eq!((s.lds, s.mem), (0, 0)); + let s = at(100, 0); + assert_eq!((s.lds, s.mem), (2000, 0)); + let s = at(0, 100); + assert_eq!((s.lds, s.mem), (0, 2000)); + // 10 % and 30 % of 2000 operations, give or take what the seed draws + let s = at(10, 30); + assert!((150..250).contains(&s.lds) && (500..700).contains(&s.mem), "{s:?}"); + assert_eq!((s.buffer, s.image), (0, 0)); + let res = |buffer_pct, image_pct| shape(&program(&Knobs { ops: 2000, lds_pct: 0, mem_pct: 0, buffer_pct, image_pct, ..Knobs::default() })); + let s = res(100, 0); + assert_eq!((s.buffer, s.image, s.lds, s.mem), (2000, 0, 0, 0)); + let s = res(0, 100); + assert_eq!((s.buffer, s.image, s.lds, s.mem), (0, 2000, 0, 0)); + let s = res(10, 5); + assert!((150..250).contains(&s.buffer) && (50..150).contains(&s.image), "{s:?}"); +} + +#[test] +fn compute_knob_translates_as_a_compute_shader() { + use xcl::gpu::recomp::Mode; + let k = Knobs { compute: true, ..Knobs::default() }; + assert!(matches!(&k.options().mode, Mode::Compute(cs) if cs.threads == [64, 1, 1] && cs.user_sgprs == 4), "{:?}", k.options().mode); + assert_eq!(Knobs::default().options().mode, Mode::Kernel); + // the same code translates differently in the two modes + let code = program(&k); + assert_ne!(translate(&code, &k.options()).unwrap().hlsl, translate(&code, &Knobs::default().options()).unwrap().hlsl); +} + +#[test] +fn buffer_and_image_knobs_at_zero_keep_the_programs_of_the_first_version() { + // FNV-1a of the programs the generator gave before it had buffer and image accesses, so the + // benchmark's programs stay comparable across commits + let fnv = |b: &[u8]| b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &x| (h ^ x as u64).wrapping_mul(0x100_0000_01b3)); + let ks = [Knobs::default(), Knobs { ops: 2000, if_depth: 6, divergent_pct: 40, loops: 3, loop_depth: 2, wave64: false, seed: 7, ..Knobs::default() }]; + assert_eq!(ks.map(|k| fnv(&program(&k))), [GOLDEN_DEFAULT, GOLDEN_MIXED]); +} + +#[test] +fn vgprs_stay_in_the_pool() { + for vgprs in [2, 16, 200] { + let s = shape(&program(&Knobs { ops: 3000, vgprs, ..Knobs::default() })); + // v0 and v1 are the lane id and offset; the pool is v2..v(vgprs + 1) + assert_eq!(s.max_vgpr, vgprs + 1, "vgprs {vgprs}"); + } +} + +#[test] +fn every_program_translates_completely() { + let mut n = 0; + for wave64 in [true, false] { + for (if_depth, loops, loop_depth) in [(0, 0, 1), (2, 1, 1), (4, 2, 3), (8, 4, 2)] { + for (lds_pct, mem_pct, buffer_pct, image_pct, compute) in [(0, 0, 0, 0, false), (5, 10, 0, 0, false), (20, 40, 0, 0, false), (5, 10, 10, 5, false), (5, 10, 10, 5, true), (0, 0, 0, 0, true)] { + let k = Knobs { seed: n, ops: 300, if_depth, divergent_pct: 25, loops, loop_depth, wave64, lds_pct, mem_pct, buffer_pct, image_pct, compute, ..Knobs::default() }; + let code = program(&k); + let insts = lines(&code).len(); + for structured in [true, false] { + let t = translate(&code, &Options { structured, ..k.options() }).unwrap_or_else(|e| panic!("{k:?}: {e}")); + assert!(t.complete(), "{k:?}: {:?}", t.unsupported_why); + assert_eq!(t.instructions, insts, "{k:?}"); + } + n += 1; + } + } + } +} + +/// `buffer_and_image_knobs_at_zero_keep_the_programs_of_the_first_version`: computed with the +/// generator of 5ae62c5 (1 536 and 32 688 bytes) +const GOLDEN_DEFAULT: u64 = 0x2365_3488_bf15_5939; +const GOLDEN_MIXED: u64 = 0xa184_a8b7_f231_29f2; + +#[test] +fn dxc_compiles_the_generated_programs() { + if let Err(e) = dxc::location() { + println!("DXC unavailable – skipping ({e})"); + runner::skip_test("no DXC"); + return; + } + let var = std::env::var("XCL_COMPILE_BENCH").unwrap_or_default(); + let (set, cases, default_reps) = match var.as_str() { + "" => ("small", measure::small(), 1), + "full" => ("full", measure::full(), 3), + "large" => ("large", measure::large(), 3), + x => panic!("XCL_COMPILE_BENCH={x}: only `full` or `large` (or unset for the small set)"), + }; + let reps = std::env::var("XCL_COMPILE_BENCH_REPS").map(|r| r.parse().expect("XCL_COMPILE_BENCH_REPS")).unwrap_or(default_reps); + let args_var = std::env::var("XCL_COMPILE_BENCH_DXC_ARGS").unwrap_or_default(); + let args: Vec<&str> = args_var.split_whitespace().collect(); + let mut rows: Vec = cases.iter().map(|c| measure::measure(c, reps, &args)).collect(); + rows.sort_by(|a, b| a.name.cmp(&b.name)); + assert_eq!(rows.len(), cases.len()); + for r in measure::by_time(&rows) { + println!( + "{:<32} {:>6} insts {:>9} B HLSL {:>8} B DXIL DXC {:>9.1} ms (min {:.1})", + r.name, r.instructions, r.hlsl_bytes, r.dxil_bytes, r.dxc_ms_median, r.dxc_ms_min + ); + } + let s = measure::summary(&rows); + println!( + "{} programs: DXC median {:.1} ms, p90 {:.1} ms, max {:.1} ms, total {:.1} ms; the slowest tenth takes {:.0} % of it", + s.programs, s.dxc_ms_median, s.dxc_ms_p90, s.dxc_ms_max, s.dxc_ms_total, s.slowest_tenth_share * 100.0 + ); + if let Ok(dir) = std::env::var("XCL_COMPILE_BENCH_OUT") { + measure::write(std::path::Path::new(&dir), &measure::environment(set, reps), &rows); + println!("written: {dir}\\compile_bench.json, compile_bench.csv"); + } +} + +#[test] +fn results_are_written_as_json_and_csv() { + let row = measure::Row { + name: "x".into(), + knobs: Knobs::default(), + split_wave64: true, + mem_windows: 4, + structured: true, + instructions: 10, + blocks: 2, + code_bytes: 40, + hlsl_bytes: 1000, + translate_ms: 0.5, + dxc_args: "-O1".into(), + dxc_ms: vec![2.0, 1.0, 3.0], + dxc_ms_median: 2.0, + dxc_ms_min: 1.0, + dxil_bytes: 300, + }; + let dir = std::env::temp_dir().join(format!("xcl_compile_bench_{}", std::process::id())); + measure::write(&dir, &serde_json::json!({ "set": "small" }), &[row.clone(), measure::Row { name: "y".into(), ..row }]); + let json: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(dir.join("compile_bench.json")).unwrap()).unwrap(); + assert_eq!(json["environment"]["set"], "small"); + assert_eq!((json["summary"]["programs"].as_u64(), json["summary"]["dxc_ms_max"].as_f64()), (Some(2), Some(2.0))); + assert_eq!(json["programs"][1]["name"], "y"); + assert_eq!((json["programs"][0]["ops"].as_u64(), json["programs"][0]["dxil_bytes"].as_u64()), (Some(200), Some(300)), "knobs are flattened into the row"); + let csv = std::fs::read_to_string(dir.join("compile_bench.csv")).unwrap(); + let lines: Vec<&str> = csv.lines().collect(); + assert_eq!(lines.len(), 3, "{csv}"); + let header: Vec<&str> = lines[0].split(',').collect(); + let first: Vec<&str> = lines[1].split(',').collect(); + assert_eq!(header.len(), first.len(), "{csv}"); + let col = |n: &str| first[header.iter().position(|h| *h == n).unwrap_or_else(|| panic!("no column {n}: {csv}"))]; + assert_eq!((col("name"), col("dxc_ms"), col("dxil_bytes"), col("wave64")), ("x", "2.0;1.0;3.0", "300", "true")); + std::fs::remove_dir_all(&dir).unwrap(); +} + +fn timed(name: &str, dxc_ms_median: f64) -> measure::Row { + measure::Row { + name: name.into(), + knobs: Knobs::default(), + split_wave64: false, + mem_windows: 1, + structured: true, + instructions: 0, + blocks: 0, + code_bytes: 0, + hlsl_bytes: 0, + translate_ms: 0.0, + dxc_args: String::new(), + dxc_ms: vec![dxc_ms_median], + dxc_ms_median, + dxc_ms_min: dxc_ms_median, + dxil_bytes: 0, + } +} + +#[test] +fn the_summary_shows_the_slow_tail() { + // 20 programs of 1..=20 ms, out of order: the slowest tenth is 19 + 20 of 210 ms + let rows: Vec = (1..=20).map(|i| timed(&format!("p{i:02}"), f64::from((i * 7) % 20 + 1))).collect(); + let s = measure::summary(&rows); + assert_eq!( + (s.programs, s.dxc_ms_total, s.dxc_ms_median, s.dxc_ms_p90, s.dxc_ms_max), + (20, 210.0, 10.5, 18.0, 20.0) + ); + assert!((s.slowest_tenth_share - 39.0 / 210.0).abs() < 1e-12, "{s:?}"); + // one program: it is the median, the p90, the maximum and the whole tenth + let one = measure::summary(&[timed("a", 5.0)]); + assert_eq!((one.dxc_ms_median, one.dxc_ms_p90, one.dxc_ms_max, one.slowest_tenth_share), (5.0, 5.0, 5.0, 1.0)); + assert_eq!(measure::summary(&[]).programs, 0); +} + +#[test] +fn rows_rank_from_the_slowest_compile() { + let rows = [timed("b", 1.0), timed("c", 9.0), timed("a", 1.0), timed("d", 4.0)]; + let names: Vec<&str> = measure::by_time(&rows).iter().map(|r| r.name.as_str()).collect(); + assert_eq!(names, ["c", "d", "a", "b"]); +} + +#[test] +fn the_large_set_is_the_tail_in_both_forms() { + let cases = measure::large(); + let names: std::collections::BTreeSet<&str> = cases.iter().map(|c| c.name.as_str()).collect(); + assert_eq!(names.len(), cases.len(), "names are unique"); + assert!(cases.iter().all(|c| c.knobs.ops >= 8000), "only large programs"); + assert_eq!(cases.iter().map(|c| c.knobs.ops).max(), Some(40000)); + let split = cases.iter().filter(|c| c.options.split_wave64 && c.options.mem_windows == 4).count(); + assert_eq!((cases.len(), split), (18, 9), "each program native and split, 4 windows"); +} diff --git a/crates/xcl/tests/compile_bench/measure.rs b/crates/xcl/tests/compile_bench/measure.rs new file mode 100644 index 000000000..26d786884 --- /dev/null +++ b/crates/xcl/tests/compile_bench/measure.rs @@ -0,0 +1,243 @@ +//! The measurement: each generated program is translated to HLSL and compiled with DXC, one +//! compile at a time, and its sizes and times are written as JSON and CSV. +//! +//! - `XCL_COMPILE_BENCH=full`: the full set (sizes up to 20 000 operations); `large`: only the +//! multi-megabyte programs (up to 40 000 operations); unset: a small set that runs in seconds, +//! so CI and every test run go through the same code +//! - `XCL_COMPILE_BENCH_OUT=`: write `compile_bench.json` and `compile_bench.csv` there +//! - `XCL_COMPILE_BENCH_REPS=`: compiles per program (default 1, full set 3) +//! - `XCL_COMPILE_BENCH_DXC_ARGS="-O1 …"`: extra DXC arguments; unset, `dxc.rs` picks the +//! optimisation level from the source size, as it does for a title +//! +//! Times are wall-clock and only comparable on one machine; run the full set with nothing else +//! running (`--test-threads=1`). + +use std::time::Instant; + +use serde::Serialize; +use xcl::gpu::recomp::{dxc, translate, Options}; + +use crate::gen::{program, Knobs}; + +#[derive(Debug, Clone, Serialize)] +pub struct Row { + pub name: String, + #[serde(flatten)] + pub knobs: Knobs, + pub split_wave64: bool, + pub mem_windows: u32, + pub structured: bool, + pub instructions: usize, + pub blocks: usize, + pub code_bytes: usize, + pub hlsl_bytes: usize, + pub translate_ms: f64, + pub dxc_args: String, + pub dxc_ms: Vec, + pub dxc_ms_median: f64, + pub dxc_ms_min: f64, + pub dxil_bytes: usize, +} + +/// A program of the set: its name, knobs and the recompiler options it is translated with. +pub struct Case { + pub name: String, + pub knobs: Knobs, + pub options: Options, +} + +fn case(name: &str, knobs: Knobs, split: bool, windows: u32, structured: bool) -> Case { + let options = Options { split_wave64: split, mem_windows: windows, structured, ..knobs.options() }; + Case { name: name.to_string(), knobs, options } +} + +/// The small set: one program per kind of control flow, wave size and form, a few hundred +/// operations each. +pub fn small() -> Vec { + let k = |ops| Knobs { ops, ..Knobs::default() }; + vec![ + case("w64", k(300), false, 1, true), + case("w32", Knobs { wave64: false, ..k(300) }, false, 1, true), + case("w64-split-4win", k(300), true, 4, true), + case("loops", Knobs { loops: 2, loop_depth: 2, ..k(300) }, false, 1, true), + case("divergent", Knobs { if_depth: 4, divergent_pct: 40, ..k(300) }, false, 1, true), + case("cs-resources", Knobs { compute: true, buffer_pct: 10, image_pct: 5, ..k(300) }, false, 1, true), + ] +} + +/// The full set: five shapes at four sizes, each in the form a 64-lane GPU gets and the one a +/// 32-lane GPU gets (split wave64, 4 memory windows), plus controls whose effect on the HLSL is +/// known (the guarded block chain, 1 against 4 memory windows). +pub fn full() -> Vec { + let mut v = Vec::new(); + for ops in [500, 2000, 8000, 20000] { + let shapes = [ + ("base", Knobs { ops, ..Knobs::default() }), + ("divergent", Knobs { ops, if_depth: 6, divergent_pct: 40, ..Knobs::default() }), + ("loops", Knobs { ops, loops: 4, loop_depth: 3, ..Knobs::default() }), + ("resources", Knobs { ops, compute: true, mem_pct: 10, buffer_pct: 10, image_pct: 5, ..Knobs::default() }), + ("w32", Knobs { ops, wave64: false, ..Knobs::default() }), + ]; + for (shape, knobs) in shapes { + v.push(case(&format!("{shape}-{ops}"), knobs.clone(), false, 1, true)); + if knobs.wave64 { + v.push(case(&format!("{shape}-{ops}-split-4win"), knobs, true, 4, true)); + } + } + let base = Knobs { ops, ..Knobs::default() }; + v.push(case(&format!("control-guarded-chain-{ops}"), base.clone(), false, 1, false)); + v.push(case(&format!("control-4win-{ops}"), base, false, 4, true)); + } + v +} + +/// The large set: only the multi-megabyte tail, where most of the compile time goes. Three +/// shapes at 8 000, 20 000 and 40 000 operations, in both forms; the larger ones cross the +/// source sizes at which `dxc.rs` lowers the optimisation level. +pub fn large() -> Vec { + let mut v = Vec::new(); + for ops in [8000, 20000, 40000] { + let shapes = [ + ("base", Knobs { ops, ..Knobs::default() }), + ("divergent", Knobs { ops, if_depth: 6, divergent_pct: 40, ..Knobs::default() }), + ("resources", Knobs { ops, compute: true, mem_pct: 10, buffer_pct: 10, image_pct: 5, ..Knobs::default() }), + ]; + for (shape, knobs) in shapes { + v.push(case(&format!("{shape}-{ops}"), knobs.clone(), false, 1, true)); + v.push(case(&format!("{shape}-{ops}-split-4win"), knobs, true, 4, true)); + } + } + v +} + +/// The set's DXC times (each program's median), so the slow tail shows next to the typical +/// program: the nearest-rank p90, the maximum, and the share of the total compile time spent +/// on the slowest tenth of the programs (at least one). +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct Summary { + pub programs: usize, + pub dxc_ms_total: f64, + pub dxc_ms_median: f64, + pub dxc_ms_p90: f64, + pub dxc_ms_max: f64, + pub slowest_tenth_share: f64, +} + +pub fn summary(rows: &[Row]) -> Summary { + let mut t: Vec = rows.iter().map(|r| r.dxc_ms_median).collect(); + t.sort_by(f64::total_cmp); + let n = t.len(); + let total: f64 = t.iter().sum(); + let tenth: f64 = t.iter().rev().take(n.div_ceil(10)).sum(); + Summary { + programs: n, + dxc_ms_total: total, + dxc_ms_median: if n > 0 { median(&t) } else { 0.0 }, + dxc_ms_p90: if n > 0 { t[(n * 9).div_ceil(10) - 1] } else { 0.0 }, + dxc_ms_max: t.last().copied().unwrap_or(0.0), + slowest_tenth_share: if total > 0.0 { tenth / total } else { 0.0 }, + } +} + +/// The rows from the slowest DXC compile to the fastest (ties by name). +pub fn by_time(rows: &[Row]) -> Vec<&Row> { + let mut v: Vec<&Row> = rows.iter().collect(); + v.sort_by(|a, b| b.dxc_ms_median.total_cmp(&a.dxc_ms_median).then_with(|| a.name.cmp(&b.name))); + v +} + +fn median(v: &[f64]) -> f64 { + let mut s = v.to_vec(); + s.sort_by(f64::total_cmp); + if s.len() % 2 == 1 { s[s.len() / 2] } else { (s[s.len() / 2 - 1] + s[s.len() / 2]) / 2.0 } +} + +fn ms(t: Instant) -> f64 { + (t.elapsed().as_secs_f64() * 1e6).round() / 1e3 +} + +/// Translate and compile one program `reps` times. Panics when it does not translate completely, +/// DXC refuses it, or a repeat gives different HLSL or DXIL. +pub fn measure(c: &Case, reps: usize, dxc_args: &[&str]) -> Row { + let code = program(&c.knobs); + let t0 = Instant::now(); + let t = translate(&code, &c.options).unwrap_or_else(|e| panic!("{}: {e}", c.name)); + let translate_ms = ms(t0); + assert!(t.complete(), "{}: {:?}", c.name, t.unsupported_why); + assert_eq!(translate(&code, &c.options).unwrap().hlsl, t.hlsl, "{}: the HLSL differs between two translations", c.name); + let (mut times, mut dxil_bytes) = (Vec::new(), None); + for _ in 0..reps { + let t0 = Instant::now(); + let dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", dxc_args).unwrap_or_else(|e| panic!("{}: {}", c.name, e.lines().next().unwrap_or(""))); + times.push(ms(t0)); + assert!(!dxil.is_empty(), "{}: empty DXIL", c.name); + assert_eq!(*dxil_bytes.get_or_insert(dxil.len()), dxil.len(), "{}: the DXIL size differs between compiles", c.name); + } + Row { + name: c.name.clone(), + knobs: c.knobs.clone(), + split_wave64: c.options.split_wave64, + mem_windows: c.options.mem_windows, + structured: c.options.structured, + instructions: t.instructions, + blocks: t.blocks, + code_bytes: code.len(), + hlsl_bytes: t.hlsl.len(), + translate_ms, + dxc_args: dxc_args.join(" "), + dxc_ms_median: median(×), + dxc_ms_min: times.iter().copied().fold(f64::INFINITY, f64::min), + dxc_ms: times, + dxil_bytes: dxil_bytes.unwrap_or(0), + } +} + +fn git(args: &[&str]) -> String { + std::process::Command::new("git") + .args(args) + .current_dir(env!("CARGO_MANIFEST_DIR")) + .output() + .ok() + .filter(|o| o.status.success()) + .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string()) + .unwrap_or_default() +} + +/// What the numbers depend on: the code's commit, the DXC, the build and the machine. +pub fn environment(set: &str, reps: usize) -> serde_json::Value { + let var = |n: &str| std::env::var(n).unwrap_or_default(); + serde_json::json!({ + "set": set, + "reps": reps, + "commit": git(&["rev-parse", "HEAD"]), + "dirty": !git(&["status", "--porcelain"]).is_empty(), + "dxc": dxc::toolchain(), + "profile": if cfg!(debug_assertions) { "debug" } else { "release" }, + "cpu": var("PROCESSOR_IDENTIFIER"), + "logical_cpus": std::thread::available_parallelism().map(|n| n.get()).unwrap_or(0), + }) +} + +/// `compile_bench.json` ({environment, summary, programs}) and `compile_bench.csv` (one row per +/// program, columns in name order; the compile times joined with `;`). +pub fn write(dir: &std::path::Path, env: &serde_json::Value, rows: &[Row]) { + std::fs::create_dir_all(dir).unwrap(); + let programs: Vec = rows.iter().map(|r| serde_json::to_value(r).unwrap()).collect(); + let json = serde_json::json!({ "environment": env, "summary": summary(rows), "programs": programs }); + std::fs::write(dir.join("compile_bench.json"), serde_json::to_string_pretty(&json).unwrap() + "\n").unwrap(); + let cell = |v: &serde_json::Value| match v { + serde_json::Value::Array(a) => a.iter().map(|x| x.to_string()).collect::>().join(";"), + serde_json::Value::String(s) => s.clone(), + x => x.to_string(), + }; + let mut csv = String::new(); + if let Some(serde_json::Value::Object(first)) = programs.first() { + csv += &first.keys().cloned().collect::>().join(","); + csv += "\n"; + for p in &programs { + csv += &p.as_object().unwrap().values().map(cell).collect::>().join(","); + csv += "\n"; + } + } + std::fs::write(dir.join("compile_bench.csv"), csv).unwrap(); +} diff --git a/scripts/compile_bench.ps1 b/scripts/compile_bench.ps1 new file mode 100644 index 000000000..f55fc97a6 --- /dev/null +++ b/scripts/compile_bench.ps1 @@ -0,0 +1,46 @@ +# Compile-time benchmark on generated RDNA2 programs (crates/xcl/tests/compile_bench): no game +# data, DXC on the CPU, no GPU needed. Builds release, compiles each program one at a time and +# writes compile_bench.json / .csv and the log to the output folder. +# .\scripts\compile_bench.ps1 # full set, 3 compiles per program +# .\scripts\compile_bench.ps1 -Set small -Reps 1 # the set every test run uses +# .\scripts\compile_bench.ps1 -Set large # only the multi-megabyte programs +# .\scripts\compile_bench.ps1 -DxcArgs '-O1' # extra DXC arguments +# Compare two runs (e.g. main and a PR's head, same machine): +# python -I scripts/compile_bench_compare.py \compile_bench.json \compile_bench.json +param( + [ValidateSet('full', 'large', 'small')][string]$Set = 'full', + [int]$Reps = 0, + [string]$DxcArgs = '', + [string]$Out = '' +) +$ErrorActionPreference = 'Stop' +Set-Location (Join-Path $PSScriptRoot '..') +$null = Get-Command cargo -ErrorAction Stop +$commit = (git rev-parse HEAD).Trim() +$dirty = [bool](git status --porcelain) +if ($dirty) { Write-Warning 'uncommitted changes: the results say "dirty": true and do not stand for a commit' } +if (-not $Out) { $Out = Join-Path 'target\compile_bench' ($commit.Substring(0, 10) + $(if ($dirty) { '-dirty' } else { '' })) } +New-Item -ItemType Directory -Force $Out | Out-Null +$log = Join-Path $Out 'compile_bench.log' + +$env:XCL_COMPILE_BENCH = if ($Set -eq 'small') { '' } else { $Set } +$env:XCL_COMPILE_BENCH_OUT = (Resolve-Path $Out).Path +$env:XCL_COMPILE_BENCH_REPS = if ($Reps -gt 0) { "$Reps" } else { '' } +$env:XCL_COMPILE_BENCH_DXC_ARGS = $DxcArgs +# Windows PowerShell 5.1 treats redirected native stderr as an error even when Cargo succeeds +$ErrorActionPreference = 'Continue' +try { + # one compile at a time: nothing else in the test binary runs beside the measurement + cargo test --release -p xcl --test compile_bench dxc_compiles_the_generated_programs -- --exact --test-threads=1 --nocapture 2>&1 | + ForEach-Object { "$_" } | Tee-Object -Variable lines | Write-Host + $code = $LASTEXITCODE +} finally { + foreach ($v in 'XCL_COMPILE_BENCH', 'XCL_COMPILE_BENCH_OUT', 'XCL_COMPILE_BENCH_REPS', 'XCL_COMPILE_BENCH_DXC_ARGS') { Remove-Item "env:$v" -ErrorAction SilentlyContinue } +} +$lines | Out-File -FilePath $log -Encoding utf8 +if ($code -eq 0 -and -not (Test-Path (Join-Path $Out 'compile_bench.json'))) { + Write-Warning 'no compile_bench.json: the test was skipped (no DXC?), see the log' + $code = 1 +} +Write-Host "commit $commit$(if ($dirty) { ' (dirty)' }), results and log: $Out" +exit $code diff --git a/scripts/compile_bench_compare.py b/scripts/compile_bench_compare.py new file mode 100644 index 000000000..ef71bfc3b --- /dev/null +++ b/scripts/compile_bench_compare.py @@ -0,0 +1,155 @@ +"""Compare two runs of the compile-time benchmark (`compile_bench.json` from +`scripts/compile_bench.ps1`), e.g. `main` against a pull request's head, program by program. + + python -I scripts/compile_bench_compare.py [--noise 0.05] + +Prints a Markdown table: instructions, HLSL bytes, DXIL bytes and the median DXC time of each +program in both runs, with the head / base ratio, and the geometric mean of the ratios. The sizes +are deterministic for one DXC; the times are only comparable when both runs come from the same +machine, build and DXC, which the environment check at the top says. A size change is marked +whatever its size; a time change only beyond the run-to-run noise (`--noise`, a fraction). It +reports, it does not +judge: the exit status is 0 whatever the numbers are (2 for unreadable input). +""" + +import json +import math +import sys + +# what the times depend on: a difference here makes them not comparable +SAME_FOR_TIMES = ("profile", "cpu", "logical_cpus", "set", "reps") + +# the run-to-run spread of a program's median DXC time on one machine, with margin: on a +# Ryzen 5 3600 the small set's medians moved by at most 1.9 % over 5 runs, and the 3 compiles +# of one full-set run by 1.4–2.8 % (median), single compiles by up to 17 % +TIME_NOISE = 0.05 + + +def load(path): + with open(path, encoding="utf-8") as f: + doc = json.load(f) + return doc["environment"], {p["name"]: p for p in doc["programs"]} + + +def dxc_version(env): + return ((env.get("dxc") or {}).get("dxcompiler") or {}).get("file_version", "") + + +def environment_notes(base, head): + notes = [] + for side, env in (("base", base), ("head", head)): + if env.get("dirty"): + notes.append(f"{side} was measured with uncommitted changes") + if dxc_version(base) != dxc_version(head): + notes.append(f"different DXC: {dxc_version(base) or '?'} / {dxc_version(head) or '?'} (sizes and times not comparable)") + for key in SAME_FOR_TIMES: + if base.get(key) != head.get(key): + notes.append(f"different {key}: {base.get(key)!r} / {head.get(key)!r} (times not comparable)") + return notes + + +def ratio(a, b): + return b / a if a else math.nan + + +def geomean(values): + values = [v for v in values if v > 0 and not math.isnan(v)] + return math.exp(sum(math.log(v) for v in values) / len(values)) if values else math.nan + + +def changed(row, noise): + """"size" when the HLSL or DXIL size differs, else "time" when the DXC time moved by more + than `noise` either way, else "".""" + if row["hlsl"][0] != row["hlsl"][1] or row["dxil"][0] != row["dxil"][1]: + return "size" + r = row["dxc"][2] + return "time" if not math.isnan(r) and (r > 1 + noise or r < 1 / (1 + noise)) else "" + + +def compare(base, head, noise=TIME_NOISE): + """{rows, only_base, only_head, means, size_changes, time_changes, noise} for two + {name: program} maps.""" + rows = [] + for name in sorted(set(base) & set(head)): + b, h = base[name], head[name] + rows.append({ + "name": name, + "instructions": (b["instructions"], h["instructions"]), + "hlsl": (b["hlsl_bytes"], h["hlsl_bytes"], ratio(b["hlsl_bytes"], h["hlsl_bytes"])), + "dxil": (b["dxil_bytes"], h["dxil_bytes"], ratio(b["dxil_bytes"], h["dxil_bytes"])), + "dxc": (b["dxc_ms_median"], h["dxc_ms_median"], ratio(b["dxc_ms_median"], h["dxc_ms_median"])), + }) + means = {k: geomean([r[k][2] for r in rows]) for k in ("hlsl", "dxil", "dxc")} + for r in rows: + r["changed"] = changed(r, noise) + size_changes = sum(1 for r in rows if r["changed"] == "size") + return { + "rows": rows, + "only_base": sorted(set(base) - set(head)), + "only_head": sorted(set(head) - set(base)), + "means": means, + "size_changes": size_changes, + "time_changes": sum(1 for r in rows if r["changed"] == "time"), + "noise": noise, + } + + +def fmt_ratio(r): + return "–" if math.isnan(r) else f"{r:.3f}" + + +def render(base_env, head_env, result): + out = [ + f"base `{base_env.get('commit', '')[:10]}` / head `{head_env.get('commit', '')[:10]}`, " + f"set {head_env.get('set')}, DXC {dxc_version(head_env) or '?'}, {head_env.get('profile')}", + "", + ] + notes = environment_notes(base_env, head_env) + out += [f"- note: {note}" for note in notes] + ([""] if notes else []) + out += [ + "| program | instructions | HLSL bytes | × | DXIL bytes | × | DXC ms (median) | × | changed |", + "|---|---:|---:|---:|---:|---:|---:|---:|---|", + ] + for r in result["rows"]: + (ib, ih), (hb, hh, hr), (db, dh, dr), (tb, th, tr) = r["instructions"], r["hlsl"], r["dxil"], r["dxc"] + insts = str(ib) if ib == ih else f"{ib} → {ih}" + out.append(f"| {r['name']} | {insts} | {hb} → {hh} | {fmt_ratio(hr)} | {db} → {dh} | {fmt_ratio(dr)} | {tb:.1f} → {th:.1f} | {fmt_ratio(tr)} | {r['changed']} |") + m = result["means"] + out += [ + "", + f"geometric mean head / base over {len(result['rows'])} programs: HLSL {fmt_ratio(m['hlsl'])}, " + f"DXIL {fmt_ratio(m['dxil'])}, DXC time {fmt_ratio(m['dxc'])}; " + f"programs whose HLSL or DXIL size changed: {result['size_changes']}; " + f"whose DXC time alone moved by more than {result['noise'] * 100:g} % (the noise): {result['time_changes']}", + ] + for side in ("only_base", "only_head"): + if result[side]: + out.append(f"only in {side[5:]}: {', '.join(result[side])}") + return "\n".join(out) + + +def main(argv): + noise = TIME_NOISE + if len(argv) == 4 and argv[2] == "--noise": + try: + noise = float(argv[3]) + except ValueError: + noise = -1.0 + argv = argv[:2] + if not 0 <= noise < 10: + print("compile_bench_compare: --noise takes a fraction, e.g. 0.05", file=sys.stderr) + return 2 + if len(argv) != 2: + print(__doc__.strip().splitlines()[3].strip(), file=sys.stderr) + return 2 + try: + (base_env, base), (head_env, head) = load(argv[0]), load(argv[1]) + except (OSError, ValueError, KeyError) as e: + print(f"compile_bench_compare: {e}", file=sys.stderr) + return 2 + print(render(base_env, head_env, compare(base, head, noise))) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/scripts/test_compile_bench_compare.py b/scripts/test_compile_bench_compare.py new file mode 100644 index 000000000..f3cdb5014 --- /dev/null +++ b/scripts/test_compile_bench_compare.py @@ -0,0 +1,87 @@ +import contextlib +import io +import json +import math +import tempfile +import unittest +from pathlib import Path + +from compile_bench_compare import compare, environment_notes, geomean, main, render + + +def program(name, insts=100, hlsl=1000, dxil=300, dxc=10.0): + return {"name": name, "instructions": insts, "hlsl_bytes": hlsl, "dxil_bytes": dxil, "dxc_ms_median": dxc} + + +ENV = {"commit": "a" * 40, "dirty": False, "dxc": {"dxcompiler": {"file_version": "1.9.2602.17"}}, + "profile": "release", "cpu": "x", "logical_cpus": 12, "set": "full", "reps": 3} + + +class CompareTests(unittest.TestCase): + def test_ratios_and_geometric_mean(self): + base = {"a": program("a", dxc=10.0), "b": program("b", hlsl=2000, dxc=20.0)} + head = {"a": program("a", dxc=5.0), "b": program("b", hlsl=1000, dxc=80.0)} + r = compare(base, head) + self.assertEqual(["a", "b"], [row["name"] for row in r["rows"]]) + self.assertEqual((10.0, 5.0, 0.5), r["rows"][0]["dxc"]) + self.assertAlmostEqual(math.sqrt(0.5 * 4.0), r["means"]["dxc"]) + self.assertAlmostEqual(math.sqrt(1.0 * 0.5), r["means"]["hlsl"]) + self.assertEqual(1, r["size_changes"]) + + def test_programs_in_one_run_only_are_listed(self): + r = compare({"a": program("a"), "old": program("old")}, {"a": program("a"), "new": program("new")}) + self.assertEqual((["old"], ["new"]), (r["only_base"], r["only_head"])) + self.assertEqual(1, len(r["rows"])) + + def test_a_time_change_counts_only_beyond_the_noise(self): + base = {n: program(n, dxc=100.0) for n in "abcd"} + head = {"a": program("a", dxc=104.0), "b": program("b", dxc=110.0), "c": program("c", dxc=90.0), "d": program("d", hlsl=999, dxc=100.0)} + r = compare(base, head, noise=0.05) + self.assertEqual(["", "time", "time", "size"], [row["changed"] for row in r["rows"]]) + self.assertEqual((1, 2), (r["size_changes"], r["time_changes"])) + # a wider noise band leaves only the size change + self.assertEqual(["", "", "", "size"], [row["changed"] for row in compare(base, head, noise=0.2)["rows"]]) + + def test_geomean_skips_missing_ratios(self): + self.assertAlmostEqual(2.0, geomean([2.0, math.nan, 0.0])) + self.assertTrue(math.isnan(geomean([]))) + + +class EnvironmentTests(unittest.TestCase): + def test_same_environment_has_no_notes(self): + self.assertEqual([], environment_notes(ENV, dict(ENV, commit="b" * 40))) + + def test_differences_that_make_times_incomparable_are_noted(self): + other = dict(ENV, dirty=True, profile="debug", dxc={"dxcompiler": {"file_version": "1.8.2505.1"}}) + notes = environment_notes(ENV, other) + self.assertTrue(any("head was measured with uncommitted changes" in n for n in notes)) + self.assertTrue(any("different DXC" in n for n in notes)) + self.assertTrue(any("different profile" in n for n in notes)) + self.assertEqual(3, len(notes)) + + +class RenderTests(unittest.TestCase): + def test_table_rows_have_equal_columns(self): + r = compare({"a": program("a"), "b": program("b", insts=7)}, {"a": program("a", dxil=0), "b": program("b", insts=9)}) + lines = [l for l in render(ENV, ENV, r).splitlines() if l.startswith("|")] + self.assertEqual(4, len(lines)) + self.assertEqual(1, len({l.count("|") for l in lines})) + self.assertIn("| 7 → 9 |", lines[3]) + + def test_main_reads_files_and_rejects_bad_input(self): + with tempfile.TemporaryDirectory() as d: + p = Path(d) / "run.json" + p.write_text(json.dumps({"environment": ENV, "programs": [program("a")]}), encoding="utf-8") + self.assertEqual(0, main([str(p), str(p)])) + (Path(d) / "bad.json").write_text("{", encoding="utf-8") + self.assertEqual(2, main([str(p), str(Path(d) / "bad.json")])) + self.assertEqual(2, main([str(p)])) + out = io.StringIO() + with contextlib.redirect_stdout(out): + self.assertEqual(0, main([str(p), str(p), "--noise", "0.1"])) + self.assertIn("more than 10 % (the noise)", out.getvalue()) + self.assertEqual(2, main([str(p), str(p), "--noise", "x"])) + + +if __name__ == "__main__": + unittest.main()