diff --git a/crates/metal2vulkan-runtime/src/pipeline/sources.rs b/crates/metal2vulkan-runtime/src/pipeline/sources.rs index e5325402d..5a61f25a3 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/sources.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/sources.rs @@ -16,6 +16,10 @@ use metal2vulkan::pipeline::{ use metal2vulkan::Budget; use std::sync::Arc; +/// The translator's census name of a kernel emulated in place of the pin of its device's widest +/// mode (`WorkCounts::widest_pin_kernels_emulated`). +const WIDEST_PIN_STRATEGY: &str = "simd.emulated.widest-pin"; + /// The render pipeline artifacts this process encoded for the directory, which /// `tests::render_stage_digests`' count reads: a sweep whose stage functions the directory holds /// must encode none. Carried only where that device test is compiled, since nothing else reads @@ -123,6 +127,13 @@ impl<'a> Sources<'a> { None => compile.compile_function(function, inputs, budget)?, }; shared.counts.function_translated(); + if compiled + .strategies() + .entries + .contains_key(WIDEST_PIN_STRATEGY) + { + shared.counts.widest_pin_kernel_emulated(); + } let bytes = cache.store_function(compile, &compiled); cache.memo.keep_function(&compiled, bytes); self.note(Artifact::Function(compiled.clone())); diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index de81df55f..75b96d2ac 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -106,6 +106,7 @@ pub(crate) struct Counters { stage_entries_specialized: AtomicU64, stage_entries_shared: AtomicU64, functions_translated: AtomicU64, + widest_pin_kernels_emulated: AtomicU64, functions_shared: AtomicU64, linked_use_questions_asked: AtomicU64, descriptor_keys_built: AtomicU64, @@ -2292,6 +2293,13 @@ impl Counters { self.functions_translated.fetch_add(1, Ordering::Relaxed); } + /// A kernel the runtime translated took the emulated simdgroup tier in place of the pin of its + /// device's widest mode (`pipeline/sources.rs`). + pub(crate) fn widest_pin_kernel_emulated(&self) { + self.widest_pin_kernels_emulated + .fetch_add(1, Ordering::Relaxed); + } + /// An ask for a stage's function that found it compiled already -- in the device's memo, in a /// creation's binary archive or in the shader cache on disk -- so nothing was translated /// (`pipeline/sources.rs`). @@ -5638,6 +5646,15 @@ pub struct WorkCounts { /// translate again and make nothing: one entry, one module, and a translation this count is /// the only record of. pub functions_translated: u64, + /// Of `functions_translated`, the kernels translated on the emulated simdgroup tier (each + /// simdgroup 32 consecutive threads, its operations and barriers through workgroup memory and + /// workgroup barriers) in place of the pin to 32-lane subgroups, on a device whose compiler + /// chooses a kernel's SIMD width between a `minSubgroupSize` below 32 and a `maxSubgroupSize` + /// of 32 (ANV): a kernel of more than 256 AIR instructions whose values are estimated to hold + /// more than 36 32-bit words at once, which the pin would compile in the device's widest mode, + /// where its compile time grows to seconds and past them (`docs/API.md`, section 3). Metal pins + /// nothing: an Apple GPU runs every simdgroup 32 wide. + pub widest_pin_kernels_emulated: u64, /// Asks for a stage's function that found it compiled already, so nothing was translated: in /// the device's memo, in one of the creation's binary archives, or in the shader cache on /// disk. With `functions_translated` it adds up to every ask the run made. @@ -9820,6 +9837,8 @@ impl Device { stage_entries_specialized: counters.stage_entries_specialized.load(Ordering::Relaxed), stage_entries_shared: counters.stage_entries_shared.load(Ordering::Relaxed), functions_translated: counters.functions_translated.load(Ordering::Relaxed), + widest_pin_kernels_emulated: (counters.widest_pin_kernels_emulated) + .load(Ordering::Relaxed), functions_shared: counters.functions_shared.load(Ordering::Relaxed), linked_use_questions_asked: counters.linked_use_questions_asked.load(Ordering::Relaxed), descriptor_keys_built: counters.descriptor_keys_built.load(Ordering::Relaxed), diff --git a/crates/metal2vulkan/src/lower/select.rs b/crates/metal2vulkan/src/lower/select.rs index a35832a16..e5ad37c1e 100644 --- a/crates/metal2vulkan/src/lower/select.rs +++ b/crates/metal2vulkan/src/lower/select.rs @@ -470,6 +470,10 @@ impl Plan { if device != 0 { tally(&mut out, simd::DEVICE_LOCKSTEP.into(), device, 0); } + // A kernel emulated in place of the widest mode's pin: one use, no words. + if self.families.simd.widest_pin { + tally(&mut out, simd::WIDEST_PIN.into(), 1, 0); + } out } } @@ -1662,10 +1666,13 @@ fn finish( // A kernel compiled for dispatches with a partial simdgroup emulates its simdgroups whatever // tier the profile's subgroups give them, and depends on that variant. A kernel whose lockstep // order is only exact on emulated simdgroups emulates them on every dispatch, which no variant - // selects. + // selects, and so does a large kernel whose `Direct` tier pins the device's widest mode + // (`simd::widest_pin`), unless the emulated tier refuses it below. let model = &p.fields().subgroup; let variant = cx.inputs.emulated_simdgroups && stage == Stage::Kernel; - let tier = if variant || (cx.entry.lockstep.emulated && stage == Stage::Kernel) { + let lockstep = cx.entry.lockstep.emulated && stage == Stage::Kernel; + let widest = !variant && !lockstep && simd::widest_pin(&cx, m)?; + let mut tier = if variant || lockstep || widest { if variant { cx.facts.insert(RuntimeFact::EmulatedSimdgroups); } @@ -1691,16 +1698,23 @@ fn finish( return Err(Unsupported::not_implemented(Feature::GpuEncodedIndirectCommands).into()); } if tier == Tier::Emulated { - // The emulated tier's exchange carries its own active flags. - cx.families.simd.partly_live.clear(); - simd::workgroup::check( + match simd::workgroup::check( &mut cx, &sel.strategy, &mut sel.cross, uniformity.as_ref(), m, - )?; - } else { + ) { + // The emulated tier's exchange carries its own active flags. + Ok(()) => cx.families.simd.partly_live.clear(), + // A kernel the emulated tier refuses, which changed nothing, keeps its `Direct` tier + // where only the widest mode chose emulation. + Err(Error::Unsupported(_)) if widest => tier = Tier::Direct, + Err(e) => return Err(e), + } + cx.families.simd.widest_pin = widest && tier == Tier::Emulated; + } + if tier != Tier::Emulated { // A workgroup barrier part of the workgroup skips is walked predicated in every tier. simd::divergent::barriers( &mut cx, diff --git a/crates/metal2vulkan/src/lower/simd/divergent.rs b/crates/metal2vulkan/src/lower/simd/divergent.rs index 96ce88f14..0781774f1 100644 --- a/crates/metal2vulkan/src/lower/simd/divergent.rs +++ b/crates/metal2vulkan/src/lower/simd/divergent.rs @@ -161,16 +161,15 @@ pub fn is_sync(s: &Strategy) -> bool { } /// Plan the predicated walk of the kernel of `cx` with synchronizations `set`: the uniform and sync -/// blocks, the uniform conditions, and the values the guards demote, added to `cross` (sorted, -/// block-crossing values). The vote word is left to the caller. +/// blocks, the uniform conditions, and the values the guards demote, which the caller adds to the +/// block-crossing values once it takes the plan ([`demote`]). The vote word is left to the caller. pub fn plan( cx: &SelectCx<'_>, strategy: &[Option], u: &Uniformity, set: SyncSet, - cross: &mut Vec<(ValueId, DemoteTy)>, m: &mut Meter, -) -> Result { +) -> Result<(Predication, BTreeMap), Error> { let body = cx.body; let values = cx.values; let nb = body.blocks.len(); @@ -227,17 +226,22 @@ pub fn plan( p.uniform_conds.dedup(); let (extra, reloads) = demotions(cx, strategy, set, &home, m)?; p.reloads = reloads; - if !extra.is_empty() { - let mut all: BTreeMap = cross.drain(..).collect(); - all.extend(extra); - cross.extend(all); - } - Ok(p) + Ok((p, extra)) })(); m.release(bytes); r } +/// Add the values a predicated walk's guards demote (`extra`, [`plan`]'s) to the block-crossing +/// values `cross`, which stay sorted. +pub fn demote(cross: &mut Vec<(ValueId, DemoteTy)>, extra: BTreeMap) { + if !extra.is_empty() { + let mut all: BTreeMap = cross.drain(..).collect(); + all.extend(extra); + cross.extend(all); + } +} + /// The bytes of the workgroup word a predicated kernel outside the emulated tier votes in /// (`RuntimeFact::PredicationVote`). pub const VOTE_BYTES: u32 = 4; @@ -305,7 +309,8 @@ pub fn barriers( if !divergent && !partial { return Ok(None); } - let mut p = plan(cx, strategy, u, set, cross, m)?; + let (mut p, extra) = plan(cx, strategy, u, set, m)?; + demote(cross, extra); p.vote_word = sync_in_loop(cx, &p, m)?; p.partial_groups = partial; Ok(Some((p, divergent))) diff --git a/crates/metal2vulkan/src/lower/simd/mod.rs b/crates/metal2vulkan/src/lower/simd/mod.rs index dbf5afe68..b8072bd20 100644 --- a/crates/metal2vulkan/src/lower/simd/mod.rs +++ b/crates/metal2vulkan/src/lower/simd/mod.rs @@ -32,6 +32,51 @@ //! form; the AGX form's is unmeasured. A shuffle, broadcast, or fill from a lane past the thread //! count, or not live in a divergent block, reads all-zero bits, Metal's answer. //! +//! **The widest mode.** Where the device's compiler chooses a kernel's SIMD width itself +//! (`subgroupSizeControl` with `minSubgroupSize` below 32 and `maxSubgroupSize` 32, as ANV's +//! 8 to 32), the `Direct` tier's pin to 32 lanes with full subgroups compiles the kernel in the +//! widest mode, where each lane's value takes four times the registers of the narrowest one: a +//! kernel whose values the compiler would hold in registers at a narrower width spills there, and +//! its compile time grows to seconds and past them. A kernel the `Direct` tier would run on such a +//! device takes the `Emulated` tier instead when its entry, inlined, holds more than +//! [`WIDEST_PIN_FLOOR`] instructions and its values are estimated to hold more than +//! [`WIDEST_PIN_WORDS`] 32-bit words at once ([`pressure`], [`widest_pin`]): both tiers are exact +//! (the `Emulated` tier keeps every simdgroup operation and lockstep barrier, through workgroup +//! memory and barriers), and the emulated kernel takes no required size, so the driver chooses +//! its width. The census counts such a kernel once as [`WIDEST_PIN`]. A kernel the `Emulated` +//! tier refuses (a 64-bit exchange, a scratch beside its arena past the device's shared memory) +//! keeps the `Direct` tier. +//! +//! The bounds come from an authored kernel measured on an Iris Xe (RPL-P, ANV): `S` steps, each +//! a branch on one of `K` live `float` accumulators whose arm stores a device word and loads the +//! next (a lockstep pair in divergent flow: a subgroup barrier there), with `P` the arm's accesses +//! go through a pointer it loads from memory (a resident-set search a step), then every +//! accumulator updated. Pressure, not size, separates the cases: the driver's compile +//! (`vkCreateComputePipelines`, ms) and the GPU time of a dispatch of 12,288 threads (ms), pinned +//! (`Direct`) and emulated, one run each (compile times varied up to twice between runs): +//! +//! | `P K S` | instructions | live words | compile, `Direct` | `Emulated` | GPU, `Direct` | `Emulated` | +//! |------------|-------------:|-----------:|------------------:|-----------:|--------------:|-----------:| +//! | `0 4 32` | 818 | 12 | 20 | 35 | 0.0099 | 0.0184 | +//! | `0 16 32` | 1,994 | 24 | 63 | 73 | 0.029 | 0.028 | +//! | `0 16 128` | 7,850 | 24 | 589 | 559 | 0.129 | 0.159 | +//! | `1 4 32` | 874 | 34 | 783 | 766 | 0.010 | 0.018 | +//! | `0 32 64` | 7,050 | 40 | 6,652 | 282 | 1.061 | 0.107 | +//! | `1 16 2` | 166 | 46 | 51 | 31 | 0.0076 | 0.0050 | +//! | `1 16 4` | 290 | 46 | 117 | 61 | 0.0154 | 0.0057 | +//! | `1 16 16` | 1,042 | 46 | 971 | 300 | 0.070 | 0.015 | +//! | `1 16 64` | 4,066 | 46 | 11,987 | 2,585 | 0.319 | 0.074 | +//! | `1 16 512` | 32,290 | 46 | past 8 GiB, end | 3,292 | - | 1.709 | +//! | `1 32 32` | 3,618 | 62 | 18,428 | 996 | 1.221 | 0.051 | +//! | `1 48 32` | 5,186 | 78 | 25,799 | 1,277 | 1.985 | 0.081 | +//! +//! At 34 estimated words or fewer the two compile alike (within 1.8 times either way) and the +//! pinned kernel runs as fast or faster; from 40 the pinned compile takes 1.6 to 24 times the +//! emulated one and its GPU time 1.5 to 25 times, so [`WIDEST_PIN_WORDS`] is 36. At or below +//! [`WIDEST_PIN_FLOOR`] instructions every pinned compile measured took at most 102 ms. Answers +//! were the same bits on both tiers in every run. The estimate's own cost is linear in the body: +//! 5 ms of a 3.4 s release translation of a 162,914-instruction kernel. +//! //! **Partly live groups on subgroups**. On `Direct`, `PartialFragment` and `Cluster32`, an //! operation that reads another lane's value by its index (a matrix or AGX multiply-add's cells; a //! simdgroup or quad shuffle, shuffle-xor, relative shuffle, rotation, broadcast by lane, or fill, @@ -100,6 +145,7 @@ pub mod divergent; mod group; pub mod lockstep; pub mod matrix; +pub mod pressure; #[cfg(test)] mod tests; pub mod uniform; @@ -237,6 +283,9 @@ pub struct SimdPlan { /// `VkProperty::SimdgroupLockstep`, and the census counts them as [`DEVICE_LOCKSTEP`]. 0 /// elsewhere. pub device_lockstep: u32, + /// The kernel took the `Emulated` tier in place of the `Direct` tier's pin to the device's + /// widest mode ([`widest_pin`]), which the census counts as [`WIDEST_PIN`]. + pub widest_pin: bool, /// The operations that read another lane where some lane of the group may not take part: /// the matrix and AGX multiply-adds and the group operations that read a lane's value by its /// index ([`group::reads_lanes`]), in a kernel's blocks `uniform::Uniformity` cannot prove @@ -288,6 +337,40 @@ pub struct SimdPlan { /// The census name of the places the device's simdgroup lockstep orders, with no words. pub const DEVICE_LOCKSTEP: &str = "barrier.lockstep.device"; +/// The census name of a kernel that took the `Emulated` tier in place of the `Direct` tier's pin +/// to the device's widest mode ([`widest_pin`]): one use, no words. +pub const WIDEST_PIN: &str = "simd.emulated.widest-pin"; + +/// The instructions of a kernel's inlined entry at or below which [`widest_pin`] keeps the +/// `Direct` tier whatever its pressure (the module docs, "The widest mode"). +pub const WIDEST_PIN_FLOOR: usize = 256; + +/// The estimated peak of live 32-bit words ([`pressure::peak_words`]) above which [`widest_pin`] +/// takes the `Emulated` tier in place of the `Direct` tier's pin to the widest mode (the module +/// docs, "The widest mode"). +pub const WIDEST_PIN_WORDS: u64 = 36; + +/// Whether the kernel of `cx`, whose class the `Direct` tier runs on its device, takes the +/// `Emulated` tier instead (the module docs, "The widest mode"): the device's kernel stage pins a +/// size between a `minSubgroupSize` below 32 and a `maxSubgroupSize` of 32, and the entry holds +/// more than [`WIDEST_PIN_FLOOR`] instructions whose values are estimated to hold more than +/// [`WIDEST_PIN_WORDS`] 32-bit words at once. Read from the device's facts and the entry's +/// structure alone; the estimate runs only where the device's facts and the size call for it. +pub fn widest_pin(cx: &SelectCx<'_>, m: &mut Meter) -> Result { + let model = &cx.profile.fields().subgroup; + let st = &model.kernel; + let widest = cx.stage == Stage::Kernel + && st.pinnable + && st.sizes.min < group::SIMD_WIDTH + && st.sizes.max == group::SIMD_WIDTH + && cx.body.insts.len() > WIDEST_PIN_FLOOR + && subgroup::tier(&cx.simd, Stage::Kernel, model) == Ok(Tier::Direct); + if !widest { + return Ok(false); + } + Ok(pressure::peak_words(cx.entry, cx.body, m)? > WIDEST_PIN_WORDS) +} + /// The artifact's reconvergence: `ImplementationDefined` when the entry holds a tangled instruction /// and the profile has no maximal reconvergence. pub fn reconvergence(plan: &Plan) -> Reconvergence { diff --git a/crates/metal2vulkan/src/lower/simd/pressure.rs b/crates/metal2vulkan/src/lower/simd/pressure.rs new file mode 100644 index 000000000..85835b22d --- /dev/null +++ b/crates/metal2vulkan/src/lower/simd/pressure.rs @@ -0,0 +1,261 @@ +//! The register pressure of a kernel's entry, estimated from its structure: the most 32-bit words +//! its values hold at once, which [`super::widest_pin`] bounds. +//! +//! **Live intervals in layout order.** The body's instructions are numbered block after block +//! (the `Body` arena's order). A value is live from its definition (a parameter from the start) +//! through its last use; a phi's incoming value is used at the end of the block it comes from, and +//! a value defined before a loop and used in it is live to the loop's last instruction (a later +//! iteration reads it again). Numbering in layout order also keeps a value live across an arm of +//! a branch it is not used in, which is what a SIMT device does: it runs both arms of a divergent +//! branch, one after the other, with the value held. The estimate is the largest sum of the +//! widths of the values live at one instruction. +//! +//! **Widths are the lowered ones.** A value takes its type's 32-bit words (a narrow integer or +//! float one, a 64-bit one two, a vector its lanes', an aggregate its members'), and a pointer +//! two. A pointer loaded from memory or made from an integer, and every pointer derived from one, +//! is a wide pointer in the lowered module (`memory::roots`: four `u64`s, [`WIDE_POINTER_WORDS`]), +//! and the resident-set search that makes it holds [`SEARCH_WORDS`] more while it runs, at the +//! instruction that makes it. + +use crate::air::ir::{BlockId, Body, CastOp, Idx, InstKind, Type, TypeId, TypeTable, Value}; +use crate::air::Entry; +use crate::budget::{vec_bytes, Meter}; +use crate::error::Error; +use crate::graph::LoopForest; + +/// The 32-bit words of a wide pointer: `(root, at, host, size)`, four `u64`s. +pub const WIDE_POINTER_WORDS: u64 = 8; + +/// The 32-bit words the resident-set search holds beside what is live at its call (`memory::roots`'s +/// `search`): the table's and the set's addresses, the address searched and the entry's Metal +/// address (two words each), the first root and the count (two each), and the candidate and the +/// count left (one each). +pub const SEARCH_WORDS: u64 = 14; + +/// The passes over the body that find the wide pointers a phi carries around a loop: a phi whose +/// wide incoming value is defined later in layout order takes another pass, one per such phi in a +/// chain of them. A chain longer than this leaves its last phis counted at a pointer's two words. +const WIDE_PASSES: u32 = 8; + +/// The largest number of 32-bit words the entry's values hold at once (the module docs). Its +/// work is linear in the body's instructions and operands, and in its values for each loop; its +/// tables are charged while they live. +pub fn peak_words(entry: &Entry, body: &Body, m: &mut Meter) -> Result { + let types = entry.module.types(); + let n = body.insts.len(); + let params: Vec = match entry.module.func(entry.func).map(|f| f.ty) { + Some(ty) => match types.get(ty) { + Some(Type::Function { params, .. }) => params.to_vec(), + _ => Vec::new(), + }, + None => Vec::new(), + }; + // Per instruction: the last position reading it, and whether it is a wide pointer. + let mut last: Vec = Vec::new(); + let mut wide: Vec = Vec::new(); + let mut arg_last: Vec> = vec![None; params.len()]; + m.reserve_exact(&mut last, n)?; + m.reserve_exact(&mut wide, n)?; + let held = vec_bytes(&last) + vec_bytes(&wide) + vec_bytes(&arg_last) + vec_bytes(¶ms); + m.charge(vec_bytes(&arg_last) + vec_bytes(¶ms))?; + let r = (|| { + last.extend((0..n).map(|i| u32::try_from(i).unwrap_or(u32::MAX))); + wide.resize(n, false); + let use_at = |v: Value, at: u32, last: &mut [u32], arg_last: &mut [Option]| match v { + Value::Inst(i) => { + if let Some(l) = last.get_mut(i.index()) { + *l = (*l).max(at); + } + } + Value::Arg(a) => { + if let Some(l) = arg_last.get_mut(a.index()) { + *l = Some(l.map_or(at, |x| x.max(at))); + } + } + Value::Const(_) => {} + }; + for (_, block) in body.blocks.iter() { + for id in block.inst_ids() { + m.tick(1)?; + let Some(inst) = body.insts.get(id) else { + continue; + }; + let at = u32::try_from(id.index()).unwrap_or(u32::MAX); + match &inst.kind { + InstKind::Phi { incoming, .. } => { + for &(v, pred) in incoming.iter() { + let end = body + .blocks + .get(pred) + .map_or(at, |b| b.end.raw().saturating_sub(1)); + use_at(v, end, &mut last, &mut arg_last); + } + } + kind => kind.for_each_value(|v| use_at(v, at, &mut last, &mut arg_last)), + } + } + } + // Wide pointers, to a fixpoint over phis whose incoming value comes later in layout (a + // loop's back edge), at most `WIDE_PASSES` passes. + let is_wide = |v: Value, wide: &[bool]| match v { + Value::Inst(i) => wide.get(i.index()).copied().unwrap_or(false), + _ => false, + }; + let mut changed = true; + let mut passes = 0; + while changed && passes < WIDE_PASSES { + changed = false; + passes += 1; + for (id, inst) in body.insts.iter() { + m.tick(1)?; + if wide.get(id.index()).copied().unwrap_or(true) { + continue; + } + let pointer = matches!(types.get(inst.ty), Some(Type::Ptr { .. })); + let made = pointer + && match &inst.kind { + InstKind::Load { .. } + | InstKind::Cast { + op: CastOp::IntToPtr, + .. + } => true, + InstKind::Gep { base, .. } => is_wide(*base, &wide), + InstKind::Cast { v, .. } => is_wide(*v, &wide), + InstKind::Select { t, f, .. } => is_wide(*t, &wide) || is_wide(*f, &wide), + InstKind::Phi { incoming, .. } => { + incoming.iter().any(|&(v, _)| is_wide(v, &wide)) + } + _ => false, + }; + if made { + wide[id.index()] = true; + changed = true; + } + } + } + // A value defined before a loop and read in it is live to the loop's end: each loop that + // holds its last read, from the innermost out, whose first instruction follows its + // definition. + let loops = LoopForest::compute(&entry.cfg, m)?; + let r = (|| { + let mut spans = vec![(u32::MAX, 0u32); 0]; + m.reserve_exact(&mut spans, loops.len())?; + spans.resize(loops.len(), (u32::MAX, 0)); + let mut block_of: Vec = Vec::new(); + m.reserve_exact(&mut block_of, n)?; + for (b, block) in body.blocks.iter() { + block_of.extend(block.inst_ids().map(|_| b)); + } + for l in loops.loops() { + for b in loops.blocks(l) { + m.tick(1)?; + if let Some(block) = body.blocks.get(b) { + let span = &mut spans[l.index()]; + span.0 = span.0.min(block.start.raw()); + span.1 = span.1.max(block.end.raw().saturating_sub(1)); + } + } + } + let extend = |def: u32, l: &mut u32, m: &mut Meter| -> Result<(), Error> { + let mut lp = block_of.get(*l as usize).and_then(|&b| loops.innermost(b)); + while let Some(id) = lp { + m.tick(1)?; + let (lo, hi) = spans[id.index()]; + if def < lo { + *l = (*l).max(hi); + } + lp = loops.parent(id); + } + Ok(()) + }; + for (def, l) in last.iter_mut().enumerate() { + extend(u32::try_from(def).unwrap_or(u32::MAX), l, m)?; + } + for l in arg_last.iter_mut().flatten() { + // A parameter is defined before the body's first instruction. + let mut at = *l; + let mut lp = block_of.get(at as usize).and_then(|&b| loops.innermost(b)); + while let Some(id) = lp { + m.tick(1)?; + at = at.max(spans[id.index()].1); + lp = loops.parent(id); + } + *l = at; + } + let bytes = vec_bytes(&spans) + vec_bytes(&block_of); + m.release(bytes); + Ok::<(), Error>(()) + })(); + m.release(loops.ledger_bytes()); + r?; + // The words live at each position: a difference array, summed in order. + let mut delta: Vec = Vec::new(); + m.reserve_exact(&mut delta, n + 1)?; + delta.resize(n + 1, 0); + let mut search = vec![false; 0]; + m.reserve_exact(&mut search, n)?; + search.resize(n, false); + for (id, inst) in body.insts.iter() { + let i = id.index(); + let w = if wide[i] { + WIDE_POINTER_WORDS + } else { + words(types, inst.ty, 0) + }; + if w == 0 { + continue; + } + let made_here = wide[i] + && matches!( + inst.kind, + InstKind::Load { .. } + | InstKind::Cast { + op: CastOp::IntToPtr, + .. + } + ); + search[i] = made_here; + delta[i] += w as i64; + delta[(last[i] as usize + 1).min(n)] -= w as i64; + } + for (a, l) in arg_last.iter().enumerate() { + if let Some(l) = l { + let w = params.get(a).map_or(0, |&t| words(types, t, 0)) as i64; + delta[0] += w; + delta[(*l as usize + 1).min(n)] -= w; + } + } + let (mut live, mut peak) = (0i64, 0i64); + for (i, d) in delta.iter().take(n).enumerate() { + live += d; + let transient = if search[i] { SEARCH_WORDS as i64 } else { 0 }; + peak = peak.max(live + transient); + } + m.release(vec_bytes(&delta) + vec_bytes(&search)); + Ok(u64::try_from(peak).unwrap_or(0)) + })(); + m.release(held); + r +} + +/// The 32-bit words a value of `ty` holds in registers (the module docs); 0 for `void`, a label +/// and the like. `depth` bounds the walk into nested aggregates. +fn words(types: &TypeTable, ty: TypeId, depth: u32) -> u64 { + match types.get(ty) { + Some(Type::Int(bits)) => u64::from(bits.div_ceil(32).max(1)), + Some(Type::Half | Type::BFloat | Type::Float) => 1, + Some(Type::Double) => 2, + Some(Type::Ptr { .. }) => 2, + Some(Type::Vector { elem, len }) => { + u64::from(*len).saturating_mul(words(types, *elem, depth)) + } + Some(Type::Array { elem, len }) if depth < 4 => { + len.saturating_mul(words(types, *elem, depth + 1)) + } + Some(Type::Struct { fields, .. }) if depth < 4 => fields + .iter() + .map(|&t| words(types, t, depth + 1)) + .fold(0u64, u64::saturating_add), + _ => 0, + } +} diff --git a/crates/metal2vulkan/src/lower/simd/workgroup.rs b/crates/metal2vulkan/src/lower/simd/workgroup.rs index 4fc3b5797..46b0cefd2 100644 --- a/crates/metal2vulkan/src/lower/simd/workgroup.rs +++ b/crates/metal2vulkan/src/lower/simd/workgroup.rs @@ -319,6 +319,9 @@ pub fn arena_bytes(arena: Option, regions: u64) -> u64 { /// only tangled instructions are emulated sites and threadgroup barriers the lockstep pass placed /// keeps no reconvergence mode. `given` is the body's uniformity when the caller already holds it /// (`simd::partly_live`, which keeps its ledger bytes); otherwise it is computed and released here. +/// +/// A refusal changes nothing of `cx` or `cross`, so a kernel the emulated tier refuses can take +/// another tier (`simd::widest_pin`'s). pub fn check( cx: &mut SelectCx<'_>, strategy: &[Option], @@ -326,24 +329,6 @@ pub fn check( given: Option<&Uniformity>, m: &mut Meter, ) -> Result<(), Error> { - let computed; - let u = match given { - Some(u) => u, - None => { - computed = Uniformity::of(cx.entry, cx.body, m)?; - &computed - } - }; - let predication = match divergent_site(cx, strategy, u) { - Some(_) => { - divergent::plan(cx, strategy, u, divergent::SyncSet::Emulated, cross, m).map(Some) - } - None => Ok(None), - }; - if given.is_none() { - m.release(u.ledger_bytes()); - } - let predication = predication?; // Metal moves no 64-bit value between lanes, and AIR has no `double` group operation, so no // exchange of a 64-bit form is lowered. let wide = strategy.iter().flatten().any(|s| match s { @@ -353,6 +338,26 @@ pub fn check( if wide { return Err(Unsupported::not_implemented(Feature::Lowering(LowerFamily::Simd)).into()); } + let computed; + let u = match given { + Some(u) => u, + None => { + computed = Uniformity::of(cx.entry, cx.body, m)?; + &computed + } + }; + // The guards' demotions join `cross` only once nothing refuses. + let planned = match divergent_site(cx, strategy, u) { + Some(_) => divergent::plan(cx, strategy, u, divergent::SyncSet::Emulated, m).map(Some), + None => Ok(None), + }; + if given.is_none() { + m.release(u.ledger_bytes()); + } + let (predication, demoted) = match planned? { + Some((p, extra)) => (Some(p), Some(extra)), + None => (None, None), + }; // An emulated site's result does not depend on subgroup reconvergence, nor does a threadgroup // barrier the lockstep pass placed where the threadgroup runs together. let other_tangled = cx.tangled.iter().any(|&v| { @@ -362,10 +367,6 @@ pub fn check( .and_then(Option::as_ref) .is_some_and(emulated_site) }); - if !other_tangled { - cx.families.simd.mode = ReconvergenceMode::None; - cx.families.simd.implementation_defined = false; - } // The widest exchange: a site of a divergent block also publishes its lane's active flag (in // a uniform block every invocation is live or none is, so every lane is active and no flag // is published), and a predicated kernel's workgroup votes use the first word of the @@ -390,21 +391,32 @@ pub fn check( if predication.is_some() { words = words.max(1); } + let fact = if words == 0 { + None + } else { + let per_simdgroup = bytes_per_simdgroup(words); + // The arena the module declares (`access::local::use_arena` checked its static part) and + // its typed threadgroup objects. + let arena = crate::lower::access::local::static_workgroup_bytes(cx); + let required = arena_bytes(arena, 0).saturating_add(per_simdgroup); + crate::lower::mesh::workgroup_limit(cx).check(required)?; + Some(RuntimeFact::SimdgroupEmulation { + bytes_per_simdgroup: u32::try_from(per_simdgroup).unwrap_or(u32::MAX), + arena, + }) + }; + if let Some(extra) = demoted { + divergent::demote(cross, extra); + } + if !other_tangled { + cx.families.simd.mode = ReconvergenceMode::None; + cx.families.simd.implementation_defined = false; + } cx.families.simd.exchange_words = words; cx.families.simd.predication = predication; - if words == 0 { - return Ok(()); + if let Some(fact) = fact { + cx.facts.insert(fact); } - let per_simdgroup = bytes_per_simdgroup(words); - // The arena the module declares (`access::local::use_arena` checked its static part) and its - // typed threadgroup objects. - let arena = crate::lower::access::local::static_workgroup_bytes(cx); - let required = arena_bytes(arena, 0).saturating_add(per_simdgroup); - crate::lower::mesh::workgroup_limit(cx).check(required)?; - cx.facts.insert(RuntimeFact::SimdgroupEmulation { - bytes_per_simdgroup: u32::try_from(per_simdgroup).unwrap_or(u32::MAX), - arena, - }); Ok(()) } diff --git a/crates/metal2vulkan/src/tests/engine_simd_lockstep.rs b/crates/metal2vulkan/src/tests/engine_simd_lockstep.rs index 9b1d0dc53..d64da6576 100644 --- a/crates/metal2vulkan/src/tests/engine_simd_lockstep.rs +++ b/crates/metal2vulkan/src/tests/engine_simd_lockstep.rs @@ -2180,6 +2180,141 @@ fn a_divergent_device_pair_takes_a_tangle_barrier_where_the_entry_reconverges_ma assert_eq!(uses(&plan, "barrier.lockstep.device"), 1); } +/// How [`device_half_padded`] computes `DEVICE_HALF`'s first stored value, `t`. +#[derive(Clone, Copy)] +enum Padding { + /// `n` additions in a chain, then `n` taken off: `n + 1` instructions, two words live. + Chain(usize), + /// `k` values `t + j` live at once, summed, the sum's constant part taken off and the rest + /// divided by `k`: about `2k` instructions, `k` words live. + Fan(usize), +} + +/// `DEVICE_HALF` with its first stored value computed as `padding` says; with `arena`, that value +/// also goes through its own word of a threadgroup array of `arena` bytes first. +fn device_half_padded(padding: Padding, arena: Option) -> String { + let mut text = String::new(); + if let Some(bytes) = arena { + text.push_str(&format!( + "@big = internal unnamed_addr addrspace(3) global [{} x i32] undef, align 4\n", + bytes / 4 + )); + } + let mut chain = String::new(); + match padding { + Padding::Chain(n) => { + chain.push_str(" %p0 = add i32 %1, 1\n"); + for i in 1..n { + chain.push_str(&format!(" %p{i} = add i32 %p{}, 1\n", i - 1)); + } + chain.push_str(&format!(" %q = sub i32 %p{}, {n}\n", n - 1)); + } + Padding::Fan(k) => { + for j in 0..k { + chain.push_str(&format!(" %f{j} = add i32 %1, {j}\n")); + } + chain.push_str(" %s0 = add i32 %f0, 0\n"); + for j in 1..k { + chain.push_str(&format!(" %s{j} = add i32 %s{}, %f{j}\n", j - 1)); + } + chain.push_str(&format!( + " %r = sub i32 %s{}, {}\n %q = udiv i32 %r, {k}\n", + k - 1, + k * (k - 1) / 2 + )); + } + } + let stored = match arena { + Some(_) => { + chain.push_str( + " %bp = getelementptr inbounds i32, ptr addrspace(3) @big, i64 %3\n\ + store i32 %q, ptr addrspace(3) %bp, align 4\n\ + %b = load i32, ptr addrspace(3) %bp, align 4\n", + ); + "%b" + } + None => "%q", + }; + let body = DEVICE_HALF.replacen( + " store i32 %1, ptr addrspace(1) %4, align 4\n tail call void @air.wg.barrier", + &format!("{chain} store i32 {stored}, ptr addrspace(1) %4, align 4\n tail call void @air.wg.barrier"), + 1, + ); + assert!( + body.contains("%q = "), + "the padding replaced the first store" + ); + text.push_str(&body); + text +} + +/// A kernel whose `Direct` tier pins 32 lanes takes the `Emulated` tier instead where that pin is +/// the device's widest mode (ANV's 8 to 32: `intel-irisxe-rplp-anv`), its entry holds more than +/// `simd::WIDEST_PIN_FLOOR` instructions and their values are estimated to hold more than +/// `simd::WIDEST_PIN_WORDS` words at once (`lower::simd`, "The widest mode"): the divergent device +/// pair of `DEVICE_HALF`, its first stored value computed from that many values live at once, +/// runs predicated on emulated simdgroups, exact at every width, pins no size and is counted once +/// as `simd::WIDEST_PIN`. It keeps the `Direct` tier and its tangle barrier as it is, with as many +/// values live but too few instructions, with many instructions but two words live, on a device +/// whose 32 lanes are its only width (the RTX 5080) or its narrow one (RDNA3's 32 to 64), and +/// where the `Emulated` tier refuses it, its threadgroup memory leaving no room for one +/// simdgroup's scratch. +#[test] +fn a_pressured_kernel_takes_the_emulated_tier_in_place_of_the_widest_mode() { + use crate::lower::simd::{WIDEST_PIN, WIDEST_PIN_FLOOR, WIDEST_PIN_WORDS}; + let half = |t: u32| if t & 31 < 16 { t ^ 1 } else { t }; + let words = WIDEST_PIN_WORDS as usize; + let fan = Padding::Fan((WIDEST_PIN_FLOOR / 2 + 16).max(words + 8)); + let iris = "intel-irisxe-rplp-anv"; + let direct = |what: &str, text: &str, profile_name: &str| { + let Some(plan) = check( + "device_half", + text, + profile_name, + 64, + &[SubgroupSize::W32], + half, + ) else { + return false; + }; + assert_eq!(plan.simd.1, Tier::Direct, "{what} on {profile_name}"); + assert_eq!(uses(&plan, WIDEST_PIN), 0, "{what} on {profile_name}"); + assert_eq!(plan.subgroup.size, Some(32), "{what} on {profile_name}"); + true + }; + if !direct("as it is", DEVICE_HALF, iris) { + return; + } + direct( + "below the floor", + &device_half_padded(Padding::Fan(words + 8), None), + iris, + ); + direct( + "two words live", + &device_half_padded(Padding::Chain(2 * WIDEST_PIN_FLOOR), None), + iris, + ); + let pressured = device_half_padded(fan, None); + let Some(plan) = check("device_half", &pressured, iris, 64, &CHUNKED, half) else { + return; + }; + assert_eq!(plan.simd.1, Tier::Emulated, "pressured"); + assert_eq!(uses(&plan, WIDEST_PIN), 1, "pressured"); + assert_eq!(plan.subgroup.size, None, "pressured"); + assert!(!plan.subgroup.full_subgroups, "pressured"); + assert!(plan.families.simd.predication.is_some(), "pressured"); + for other in ["nvidia-rtx5080-laptop", "amd-rdna3-radv"] { + direct("pressured", &pressured, other); + } + // 48 KiB, the profile's `maxComputeSharedMemorySize`: no room for a simdgroup's 128 bytes. + direct( + "a refused emulation", + &device_half_padded(fan, Some(49152)), + iris, + ); +} + /// Texture calls take no device barrier: their pointer is the texture's handle. #[test] fn texture_calls_take_no_device_barrier() { diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 8df4b38bb..3d0b75411 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -3548,6 +3548,7 @@ field metal2vulkan-runtime::WorkCounts.wakes_spared pub wakes_spared: u64 field metal2vulkan-runtime::WorkCounts.watchdog_timeouts pub watchdog_timeouts: u64 field metal2vulkan-runtime::WorkCounts.wedges_declared pub wedges_declared: u64 field metal2vulkan-runtime::WorkCounts.whole_dispatches_on_partial_variants pub whole_dispatches_on_partial_variants: u64 +field metal2vulkan-runtime::WorkCounts.widest_pin_kernels_emulated pub widest_pin_kernels_emulated: u64 field metal2vulkan-runtime::WorkCounts.ycbcr_conversion_scratch_buffers pub ycbcr_conversion_scratch_buffers: u64 field metal2vulkan-runtime::WorkCounts.ycbcr_conversion_scratch_bytes pub ycbcr_conversion_scratch_bytes: u64 field metal2vulkan-runtime::WorkCounts.ycbcr_device_conversions pub ycbcr_device_conversions: u64 diff --git a/docs/API.md b/docs/API.md index 4d5677a4d..9f2f19b9d 100644 --- a/docs/API.md +++ b/docs/API.md @@ -707,6 +707,42 @@ placeholders (a kernel's local size is 1). Create each pipeline from a planned d one device pins only what that device can take; `DeviceProfile::check` tells whether another device can. +A kernel whose simdgroups run on 32-lane subgroups pins a required size of 32 with full +subgroups. On a device whose compiler chooses a kernel's SIMD width between a `minSubgroupSize` +below 32 and a `maxSubgroupSize` of 32 (ANV), that pin compiles the kernel in the device's widest +mode, where each lane's value takes four times the registers of the narrowest one. A kernel whose +entry, inlined, holds more than 256 AIR instructions and whose values are estimated to hold more +than 36 32-bit words at once (live intervals over the body in layout order, a value read in a loop +held to the loop's end) takes the emulated simdgroup tier there instead: each simdgroup is 32 +consecutive threads, its operations and lockstep barriers go through workgroup memory and +workgroup barriers, and its module pins no subgroup size, so the driver chooses the width. Both +forms are exact. The runtime counts such kernels (`WorkCounts::widest_pin_kernels_emulated`). A +kernel the emulated tier refuses (a 64-bit exchange, or a scratch that does not fit beside its +threadgroup memory) keeps the pin. + +The bounds come from an authored kernel measured on an Iris Xe (RPL-P, ANV): `S` steps, each a +branch on one of `K` live `float` accumulators whose arm stores a device word and loads the next +(a lockstep pair in divergent flow, so a subgroup barrier there), with `P` 1 the arm's accesses +going through a pointer it loads from memory (a resident-set search a step), then every +accumulator updated. Pressure, not size, separates the cases. The driver's compile time +(`vkCreateComputePipelines`) and the GPU time of a dispatch of 12,288 threads, pinned and +emulated, one run each (compile times varied up to twice between runs): + +| `P K S` | AIR instructions | estimated words | compile ms, pinned | emulated | GPU ms, pinned | emulated | +|------------|-----------------:|----------------:|-------------------:|---------:|---------------:|---------:| +| `0 16 128` | 7,850 | 24 | 589 | 559 | 0.129 | 0.159 | +| `1 4 32` | 874 | 34 | 783 | 766 | 0.010 | 0.018 | +| `0 32 64` | 7,050 | 40 | 6,652 | 282 | 1.061 | 0.107 | +| `1 16 16` | 1,042 | 46 | 971 | 300 | 0.070 | 0.015 | +| `1 16 64` | 4,066 | 46 | 11,987 | 2,585 | 0.319 | 0.074 | +| `1 48 32` | 5,186 | 78 | 25,799 | 1,277 | 1.985 | 0.081 | + +At 34 estimated words or fewer the two compile alike and the pinned kernel runs as fast or +faster; from 40 the pinned compile took 1.6 to 24 times the emulated one and its GPU time 1.5 to +25 times. At or below 256 instructions every pinned compile measured took at most 102 ms. Answers +were the same bits on both tiers. The estimate costs time linear in the body: 5 ms of a 3.4 s +release translation of a 162,914-instruction kernel. + ### What the module contains Every stage states the size and shape of its module, counted by the verifier that runs on every