diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 9b9173ac2..b9b18e4c2 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -61,7 +61,7 @@ mod tests; /// unchanged version, and its bless records the version. Independent of the crate's version and of /// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no /// history. -pub const SEMANTICS_VERSION: u32 = 2136; +pub const SEMANTICS_VERSION: u32 = 2137; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another diff --git a/crates/metal2vulkan/src/device/driver_facts.rs b/crates/metal2vulkan/src/device/driver_facts.rs index b593dcc96..17b8cae86 100644 --- a/crates/metal2vulkan/src/device/driver_facts.rs +++ b/crates/metal2vulkan/src/device/driver_facts.rs @@ -969,11 +969,6 @@ pub(crate) const DEFECTS: &[Measured] = &[ DriverId::INTEL_OPEN_SOURCE_MESA, (INTEL_VENDOR_ID, INTEL_IRIS_XE_RPL_P), ), - mesa_on( - DriverWorkaround::UniformAddressStorageReadsSlow, - DriverId::INTEL_OPEN_SOURCE_MESA, - (INTEL_VENDOR_ID, INTEL_IRIS_XE_RPL_P), - ), ]; /// The defects translation works around on the driver `description` names, on its GPU. diff --git a/crates/metal2vulkan/src/device/profile.rs b/crates/metal2vulkan/src/device/profile.rs index 9ef1abaf3..64f9c7d39 100644 --- a/crates/metal2vulkan/src/device/profile.rs +++ b/crates/metal2vulkan/src/device/profile.rs @@ -1602,20 +1602,6 @@ pub enum DriverWorkaround { /// encoders were faster with it, the most 3.67 to 3.74 ms against 2.84 to 2.87 ms. It /// changes no answer. PushReadsLengthenThreadPayload, - /// A read through a storage buffer at an address every invocation of a subgroup shares, inside - /// a loop, costs more than the same read through a uniform buffer: ANV (Mesa 26.2.6) on the - /// Iris Xe RPL-P (`deviceID` 0xa7a0) issues a per-lane SIMD16 untyped read for either, and a - /// convolution kernel whose 15- and 33-tap loops read their weights that way took 316.3 us - /// per tap through a storage view and 249.0 us per tap through a uniform view of the same - /// bytes (4896.8 and 4042.4 us a dispatch at 15 taps; job m3-max-36137). A cost fact, keyed on - /// that GPU alone. There a kernel's read-only slot that the memory plan finds read in a loop at - /// a per-instance uniform offset (`SlotPlan::uniform_loop_reads`), and whose memory no write of - /// the dispatch reaches (an unaliased argument nothing in the module writes), is read through - /// a uniform view (`lower::access`): sized to its window, or to `maxUniformBufferRange` where - /// the window does not bound it, a shape that binds more taking the variant that keeps it a - /// storage view (`RuntimeFact::UniformViewRange`). It reads the same bytes and changes no - /// answer. - UniformAddressStorageReadsSlow, } #[cfg(test)] diff --git a/crates/metal2vulkan/src/device/tests/profile.rs b/crates/metal2vulkan/src/device/tests/profile.rs index e7e1f1f9b..cd08a35d2 100644 --- a/crates/metal2vulkan/src/device/tests/profile.rs +++ b/crates/metal2vulkan/src/device/tests/profile.rs @@ -364,9 +364,8 @@ fn streamed_fingerprint_equals_the_hash_of_the_rendering() { /// translation reads: at most in the device's identity (vendor, device, driver version, type) and /// its allocation sizes, as two captures of one GPU under its two `deviceID`s do /// (`amd-780m-hawkpoint-radv` and `amd-780m-radv`, the Radeon 780M of Hawk Point and of Phoenix). -/// `intel-irisxe-rplp-anv` and `intel-uhd770-rpls-anv`, one GPU family on one driver, differ by the -/// workarounds measured on the Iris Xe alone (`DriverWorkaround::PushReadsLengthenThreadPayload`, -/// `DriverWorkaround::UniformAddressStorageReadsSlow`). +/// `intel-irisxe-rplp-anv` and `intel-uhd770-rpls-anv`, one GPU family on one driver, differ by a +/// workaround measured on the Iris Xe alone (`DriverWorkaround::PushReadsLengthenThreadPayload`). #[test] fn fingerprints_distinguish_committed_profiles() { let translated = |stem: &str| { diff --git a/crates/metal2vulkan/src/lower/access/mod.rs b/crates/metal2vulkan/src/lower/access/mod.rs index 8b5fa1cfe..7b68b48dd 100644 --- a/crates/metal2vulkan/src/lower/access/mod.rs +++ b/crates/metal2vulkan/src/lower/access/mod.rs @@ -1115,13 +1115,6 @@ fn descriptor_view(kind: ViewKind) -> DescriptorView { /// for the variant that keeps them all storage views), each slot the compile keeps a storage view /// declares it `Kept`, and a viewed `device` slot declares `UniformViewAliasing`. /// -/// On a profile that takes `DriverWorkaround::UniformAddressStorageReadsSlow`, with robust -/// descriptors (or containment off), a slot read in a loop at a per-instance uniform offset whose -/// memory nothing in the module writes is a uniform view before either fallback runs -/// ([`loop_uniform_views`]), sized as the fallback's are, and declares `UniformViewRange` as -/// `Viewed` where its window does not bound its range; a slot of the variant's -/// `storage_view_slots` stays a storage view and declares it `Kept`. -/// /// A pulled source buffer ([`pulled`]) shares the accessed slot of its Metal index, widened to a /// `Whole` storage slot that the fetch reads too (a window outside the first 2³² bytes above the /// bind offset is refused), or is a read-only `Whole` storage slot of its own; either takes part @@ -1327,28 +1320,6 @@ fn place_slots(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result, m: &mut Meter) -> Result, - lowering: &[Option], - sources: &[SlotRef], -) -> BTreeSet { - let p = cx.profile; - if !p - .workarounds() - .contains(&DriverWorkaround::UniformAddressStorageReadsSlow) - || contain::encoding(p) != Check::None - { - return BTreeSet::new(); - } - let memory = cx.memory; - let mut unwritten = unwritten_slots(cx, lowering, sources); - unwritten.retain(|&i| { - memory.slots.get(i).is_some_and(|s| { - s.uniform_loop_reads - && memory.read_only(s) - && !cx.inputs.storage_view_slots.contains(&s.slot) - }) - }); - unwritten -} - /// The string attribute by which Metal's compiler declares that a buffer argument's memory is /// reached through no other argument: every buffer argument of the AIR it emits carries it. const BUFFER_NO_ALIAS: &[u8] = b"air-buffer-no-alias"; diff --git a/crates/metal2vulkan/src/lower/simd/uniform.rs b/crates/metal2vulkan/src/lower/simd/uniform.rs index 9a11e30a4..ebe0d3947 100644 --- a/crates/metal2vulkan/src/lower/simd/uniform.rs +++ b/crates/metal2vulkan/src/lower/simd/uniform.rs @@ -77,22 +77,6 @@ //! divergent. A simdgroup's collective operations are divergent there, as for a workgroup: the //! vertices of one primitive may run in different simdgroups. //! -//! **Instances** ([`Uniformity::per_instance`]). The same values among the threads of a workgroup -//! that execute one dynamic instance of an instruction: Vulkan's dynamically uniform, which a -//! loop's divergent exit does not end inside the loop. A loop's threads that are still in it run -//! its iterations together, so a header phi is divergent only through a divergent incoming -//! value: a counter with a uniform start and a uniform step is uniform in every iteration, even -//! where threads leave the loop after different iterations. Block divergence reaches values -//! through two rules instead of the phi's divergent incoming block: -//! -//! - a phi at a **join** of a divergent branch is divergent: a block that paths from two of the -//! branch's successors reach without passing the branch again (up to its immediate -//! post-dominator, which may be one); a block that only one successor's paths reach is not, so -//! a loop header that only the back edge's paths reach is not; -//! - a value defined in a loop that holds a divergent branch, which an instruction outside the -//! loop uses, is divergent: threads may leave the loop after different iterations, each with -//! its own last value. The value is divergent inside the loop too, which only loses precision. -//! //! The analysis is one worklist over instructions and blocks, each of which turns divergent at //! most once; its memory is charged to the meter. @@ -317,46 +301,6 @@ fn per_invocation_arithmetic(callee: &Callee) -> bool { } } -/// What a run reads the loop forest for. -#[derive(Clone, Copy)] -enum Mode<'a> { - /// Whether invocations execute each block together, without the barrier contract. - Executed, - /// The same, taking the barrier contract over these loops. - UnderBarriers(&'a LoopForest), - /// The values per dynamic instance over these loops (the module docs, "Instances"). - PerInstance(&'a LoopForest), -} - -/// No label ([`Instance::label`]). -const UNLABELED: u32 = u32::MAX; - -/// The per-instance rules' state (the module docs, "Instances"). -struct Instance<'a> { - loops: &'a LoopForest, - /// By block: a join of a divergent branch, whose phis are divergent. - joins: Vec, - /// By loop: it holds a divergent branch, so its threads may leave it after different - /// iterations. - apart: Vec, - /// By instruction: divergent because an instruction outside a loop held apart uses it. - forced: Vec, - /// By block, for the branch being walked: the successor whose paths reach the block, or the - /// block itself where paths from two meet ([`UNLABELED`] for none yet). - label: Vec, - /// By block: the walk that last placed it in its region ([`Instance::walk`]). - stamp: Vec, - /// The current walk, from 1. - walk: u32, - /// The current walk's region, in reverse postorder. - region: Vec, -} - -/// The most passes a branch's join walk takes over its region before it takes every block of -/// two or more predecessors there as a join (each pass that changes nothing ends the walk; a -/// reducible region settles in three). -const JOIN_PASSES: u32 = 8; - /// One item of the worklist. #[derive(Clone, Copy)] enum Item { @@ -384,8 +328,6 @@ struct State<'a> { /// Blocks whose branch region was already marked. marked: Vec, work: Vec, - /// The per-instance rules' state, in that mode. - instance: Option>, } impl State<'_> { @@ -532,10 +474,6 @@ impl State<'_> { let Some(inst) = self.body.insts.get(i) else { return ALL; }; - let forced = |x: &Instance<'_>| x.forced.get(i.index()).copied().unwrap_or(true); - if self.instance.as_ref().is_some_and(forced) { - return ALL; - } if let Some(n) = self.tracked(inst.ty) { if let Some(lanes) = self.eval_lanes(&inst.kind, n) { return lanes; @@ -559,16 +497,9 @@ impl State<'_> { /// Whether instruction `i`, `inst`, is divergent as a whole under the current facts. fn eval_whole(&self, i: InstId, inst: &Inst) -> bool { match &inst.kind { - InstKind::Phi { incoming, .. } => match &self.instance { - Some(x) => { - let home = self.home_block(i); - x.joins.get(home.index()).copied().unwrap_or(true) - || incoming.iter().any(|(v, _)| self.value_divergent(*v)) - } - None => incoming - .iter() - .any(|(v, from)| self.value_divergent(*v) || self.block_divergent(*from)), - }, + InstKind::Phi { incoming, .. } => incoming + .iter() + .any(|(v, from)| self.value_divergent(*v) || self.block_divergent(*from)), InstKind::Load { ptr, volatile, @@ -637,207 +568,13 @@ impl State<'_> { let (lo, hi) = (at(i.index()), at(i.index() + 1)); self.users.get(lo..hi).unwrap_or(&[]) } - - /// Under the per-instance rules, what the branch that ends block `d` turning divergent does - /// (the module docs, "Instances"): the phis at its joins turn divergent, and so do the values - /// that instructions outside a loop around it use. - fn split( - &mut self, - d: BlockId, - pdom: &PostDomTree, - m: &mut Meter, - ) -> Result<(), Error> { - if self.instance.is_none() { - return Ok(()); - } - self.mark_joins(d, pdom, m)?; - self.mark_apart(d, m) - } - - /// Mark the joins of the divergent branch that ends block `d`, and queue their phis. Each - /// block of the region (what `d`'s successors reach without passing `d`, up to `d`'s immediate - /// post-dominator) takes the label of the successor whose paths reach it, or its own where - /// two labels meet there, which makes it a join; passes in reverse postorder repeat until no - /// label changes, at most [`JOIN_PASSES`] times. - fn mark_joins( - &mut self, - d: BlockId, - pdom: &PostDomTree, - m: &mut Meter, - ) -> Result<(), Error> { - let (body, cfg) = (self.body, &self.e.cfg); - let Some(x) = self.instance.as_mut() else { - return Ok(()); - }; - let stop = pdom.ipdom(d); - x.walk = x.walk.wrapping_add(1); - if x.walk == 0 { - x.stamp.iter_mut().for_each(|s| *s = 0); - x.walk = 1; - } - let walk = x.walk; - let mut succs: Vec = body.successors(d).filter(|&s| s != d).collect(); - succs.sort_unstable(); - succs.dedup(); - x.region.clear(); - let mut stack = succs.clone(); - while let Some(b) = stack.pop() { - m.tick(1)?; - let (Some(stamp), Some(label)) = - (x.stamp.get_mut(b.index()), x.label.get_mut(b.index())) - else { - continue; - }; - if b == d || *stamp == walk { - continue; - } - *stamp = walk; - *label = UNLABELED; - x.region.push(b); - if Some(b) != stop { - stack.extend(body.successors(b)); - } - } - x.region - .sort_unstable_by_key(|b| cfg.rpo_number(*b).unwrap_or(u32::MAX)); - let mut joined = Vec::new(); - let mut settled = false; - for _ in 0..JOIN_PASSES { - let mut changed = false; - for k in 0..x.region.len() { - m.tick(1)?; - let Some(&b) = x.region.get(k) else { - continue; - }; - let mut seen = UNLABELED; - let mut join = false; - let mut see = |l: u32| match seen { - UNLABELED => seen = l, - s if s != l => join = true, - _ => {} - }; - if succs.binary_search(&b).is_ok() { - see(b.raw()); - } - for p in cfg.predecessors(b) { - let i = p.index(); - if p != d && x.stamp.get(i) == Some(&walk) { - match x.label.get(i).copied().unwrap_or(UNLABELED) { - UNLABELED => {} - l => see(l), - } - } - } - let new = match join { - true => b.raw(), - false => seen, - }; - if x.label.get(b.index()) != Some(&new) { - if let Some(l) = x.label.get_mut(b.index()) { - *l = new; - } - changed = true; - } - if join { - if let Some(j) = x.joins.get_mut(b.index()).filter(|j| !**j) { - *j = true; - joined.push(b); - } - } - } - if !changed { - settled = true; - break; - } - } - if !settled { - // An unsettled region: every block where paths may meet is a join. - for k in 0..x.region.len() { - let Some(&b) = x.region.get(k) else { - continue; - }; - if cfg.predecessors(b).len() > 1 { - if let Some(j) = x.joins.get_mut(b.index()).filter(|j| !**j) { - *j = true; - joined.push(b); - } - } - } - } - for b in joined { - let Some(block) = body.blocks.get(b) else { - continue; - }; - for id in block.inst_ids() { - match body.insts.get(id).map(|i| &i.kind) { - Some(InstKind::Phi { .. }) => self.work.push(Item::Inst(id)), - _ => break, - } - } - } - Ok(()) - } - - /// Hold apart every loop around block `d`, whose branch turned divergent, not already held - /// apart (an enclosing one is when an inner one is): force divergent each value defined in - /// such a loop that an instruction outside it uses, and queue it. - fn mark_apart(&mut self, d: BlockId, m: &mut Meter) -> Result<(), Error> { - let body = self.body; - let mut chain = Vec::new(); - let mut forced = Vec::new(); - if let Some(x) = &self.instance { - let mut l = x.loops.innermost(d); - let mut inner = None; - while let Some(lp) = l { - if x.apart.get(lp.index()).copied().unwrap_or(true) { - break; - } - chain.push(lp); - for b in x.loops.blocks(lp) { - // The inner loop's values were read: a use outside this loop is outside it. - if inner.is_some_and(|i| x.loops.contains(i, b)) { - continue; - } - let Some(block) = body.blocks.get(b) else { - continue; - }; - for id in block.inst_ids() { - m.tick(1)?; - let leaves = self - .users(id) - .iter() - .any(|&u| !x.loops.contains(lp, self.home_block(u))); - if leaves && !x.forced.get(id.index()).copied().unwrap_or(true) { - forced.push(id); - } - } - } - inner = Some(lp); - l = x.loops.parent(lp); - } - } - if let Some(x) = self.instance.as_mut() { - for lp in chain { - if let Some(a) = x.apart.get_mut(lp.index()) { - *a = true; - } - } - for &id in &forced { - if let Some(f) = x.forced.get_mut(id.index()) { - *f = true; - } - } - } - self.work.extend(forced.into_iter().map(Item::Inst)); - Ok(()) - } } impl Uniformity { /// The uniformity of the blocks of `e`'s entry body. The returned structure stays charged to /// `m` ([`Uniformity::ledger_bytes`]); the analysis' own tables are released. pub fn of(e: &Entry, body: &Body, m: &mut Meter) -> Result { - Uniformity::analyze(e, body, Among::Workgroup, Mode::Executed, &[], 0, m) + Uniformity::analyze(e, body, Among::Workgroup, None, &[], 0, m) } /// [`of`](Self::of) for a dispatch whose threadgroups have one thread along the axes `unit` @@ -848,7 +585,7 @@ impl Uniformity { unit: UnitAxes, m: &mut Meter, ) -> Result { - Uniformity::analyze(e, body, Among::Workgroup, Mode::Executed, &[], unit, m) + Uniformity::analyze(e, body, Among::Workgroup, None, &[], unit, m) } /// The uniformity of the blocks and values of vertex function `e`'s entry body among the @@ -861,7 +598,7 @@ impl Uniformity { uniform: &[u32], m: &mut Meter, ) -> Result { - Uniformity::analyze(e, body, Among::Primitive, Mode::Executed, uniform, 0, m) + Uniformity::analyze(e, body, Among::Primitive, None, uniform, 0, m) } /// The uniformity of the blocks of `e`'s entry body among the invocations `among` relates, @@ -876,34 +613,14 @@ impl Uniformity { loops: &LoopForest, m: &mut Meter, ) -> Result { - Uniformity::analyze(e, body, among, Mode::UnderBarriers(loops), &[], 0, m) - } - - /// The uniformity of the values of `e`'s entry body among the invocations of one workgroup - /// that execute the same dynamic instance of an instruction (the module docs, "Instances"; - /// `loops` is the loop forest of `e`'s CFG). Its block facts are [`of`](Self::of)'s. - pub fn per_instance( - e: &Entry, - body: &Body, - loops: &LoopForest, - m: &mut Meter, - ) -> Result { - Uniformity::analyze( - e, - body, - Among::Workgroup, - Mode::PerInstance(loops), - &[], - 0, - m, - ) + Uniformity::analyze(e, body, among, Some(loops), &[], 0, m) } fn analyze( e: &Entry, body: &Body, among: Among, - mode: Mode<'_>, + contract: Option<&LoopForest>, uniform: &[u32], unit: UnitAxes, m: &mut Meter, @@ -933,32 +650,17 @@ impl Uniformity { .saturating_mul(4 + 4 + 3 * 16) .saturating_add(uses.saturating_mul(4)) .saturating_add(vector_uses.saturating_mul(16 * (LANES as usize - 1))) - .saturating_add(nb.saturating_mul(2 + 16)) - .saturating_add(match mode { - // The joins, labels, stamps and region by block, the forced flags and their - // worklist items by instruction, a walk's stack by edge, the loops' flags. - Mode::PerInstance(loops) => nb - .saturating_mul(1 + 4 + 4 + 4) - .saturating_add(n.saturating_mul(1 + 16)) - .saturating_add( - (body.blocks.iter()) - .map(|(b, _)| body.successors(b).count()) - .sum::() - .saturating_mul(4), - ) - .saturating_add(loops.len()), - _ => 0, - }); + .saturating_add(nb.saturating_mul(2 + 16)); // What the result keeps: the block, instruction, and argument flags. let kept = nb.saturating_add(n).saturating_add(e.ep.params.len()); m.charge(scratch.saturating_add(kept))?; let result = PostDomTree::compute(&e.cfg, m) .map_err(Error::from) .and_then(|pdom| { - let r = State::new(e, body, among, mode, uniform, unit, m) - .and_then(|st| match mode { - Mode::UnderBarriers(loops) => st.pin(&pdom, loops, m), - _ => Ok(st), + let r = State::new(e, body, among, uniform, unit, m) + .and_then(|st| match contract { + Some(loops) => st.pin(&pdom, loops, m), + None => Ok(st), }) .and_then(|st| st.run(&pdom, m)); m.release(pdom.ledger_bytes()); @@ -985,7 +687,6 @@ impl<'a> State<'a> { e: &'a Entry, body: &'a Body, among: Among, - mode: Mode<'a>, uniform: &[u32], unit: UnitAxes, m: &mut Meter, @@ -1075,19 +776,6 @@ impl<'a> State<'a> { users, marked: vec![false; nb], work: Vec::new(), - instance: match mode { - Mode::PerInstance(loops) => Some(Instance { - loops, - joins: vec![false; nb], - apart: vec![false; loops.len()], - forced: vec![false; n], - label: vec![UNLABELED; nb], - stamp: vec![0; nb], - walk: 0, - region: Vec::with_capacity(nb), - }), - _ => None, - }, }) } @@ -1187,7 +875,6 @@ impl<'a> State<'a> { if branch && old == 0 { let a = BlockId::new(self.home.get(i.index()).copied().unwrap_or(0)); self.mark_region(a, pdom, m)?; - self.split(a, pdom, m)?; } let us: Vec = self.users(i).to_vec(); self.work.extend(us.into_iter().map(Item::Inst)); diff --git a/crates/metal2vulkan/src/memory/plan.rs b/crates/metal2vulkan/src/memory/plan.rs index c2285b7d7..580cb7721 100644 --- a/crates/metal2vulkan/src/memory/plan.rs +++ b/crates/metal2vulkan/src/memory/plan.rs @@ -15,12 +15,7 @@ //! accessed element of a buffer table (an `array_ref` of buffers), with its access set, its //! proven [`Window`], and whether it needs its guest base (`PushField::SlotGuestBase`: //! `ptrtoint`, a stored pointer, or a cross-root compare). The slot's form and view kind are -//! `select`'s; the plan only states the facts. Among them: whether the function only reads the -//! slot ([`MemoryPlan::read_only`]), and whether it reads such a slot in a loop at an offset -//! that is not one constant and that every thread of a workgroup executing the read holds alike -//! ([`SlotPlan::uniform_loop_reads`], from `lower::simd::uniform`'s per-instance values), which -//! only a kernel on a profile that takes `DriverWorkaround::UniformAddressStorageReadsSlow` -//! asks, the one place `select` reads it. +//! `select`'s; the plan only states the facts. //! - **Threadgroup arena**: static threadgroup globals first, each at its own alignment, then the //! `[[threadgroup(n)]]` parameter regions, whose lengths are specialization inputs. The static //! size is exactly the sum of the allocations plus alignment padding: no sink word. @@ -60,16 +55,14 @@ use super::provenance::{ use super::window; use crate::air::abi::{AbiInt, Access, ImageblockKind, ParamRole}; use crate::air::ir::{ - AddrSpace, BlockId, Body, Const, ConstId, GlobalId, InstId, InstKind, Type, TypeId, - TypeLayouts, Value, ValueId, ValueIndex, + AddrSpace, Const, ConstId, GlobalId, InstId, InstKind, Type, TypeId, TypeLayouts, Value, + ValueId, ValueIndex, }; use crate::air::Entry; use crate::budget::{tree_bytes, vec_bytes, Meter}; -use crate::device::profile::{BufferAccess, DriverWorkaround}; +use crate::device::profile::BufferAccess; use crate::device::DeviceProfile; use crate::error::{Error, Feature, InternalError, InternalKind, Limit, LowerFamily, Unsupported}; -use crate::graph::LoopForest; -use crate::lower::simd::uniform::Uniformity; use crate::pipeline::interface::{AccessSet, Window}; use crate::pipeline::sym::{SlotClass, SlotRef}; @@ -107,13 +100,6 @@ pub struct SlotPlan { pub window: Option, /// The slot's guest base address is observed. pub guest_base: bool, - /// The slot is [`MemoryPlan::read_only`], and some load of it lies in a loop at an offset - /// that is not one constant, through a pointer that every thread of a workgroup executing the - /// load holds alike (`Uniformity::per_instance`): each iteration's threads read one address. - /// Found only in a kernel on a profile that takes - /// `DriverWorkaround::UniformAddressStorageReadsSlow` (`marks_uniform_loop_reads`); false - /// everywhere else. - pub uniform_loop_reads: bool, } /// An object in an arena. @@ -507,108 +493,6 @@ impl MemoryPlan { self.root_sets.get(at).map(|(_, r)| self.sets.get(*r)) } - /// Whether the function only reads slot `s`, by every proof the plan has: its accesses read - /// it and none writes it or is an atomic, its parameter is declared `air.read`, it is a - /// buffer parameter's own slot (not an argument buffer's or a buffer table element's), and no - /// buffer pointer has a dynamic root (a pointer loaded from memory or made from an integer, - /// which may reach the slot's memory). Another slot of the dispatch bound to the same memory - /// may still write it: that is the binder's fact, not the function's. - pub fn read_only(&self, s: &SlotPlan) -> bool { - s.access == AccessSet::READ - && !s.atomic - && s.declared == Access::Read - && !s.argument_buffer - && s.element.is_none() - && !self.needs.dynamic_roots - } - - /// Set [`SlotPlan::uniform_loop_reads`] of each [`read_only`](Self::read_only) slot: its - /// loads at an offset that is not one constant, through a pointer of its root alone, in a - /// loop, are read against the entry body's per-instance uniformity. The loop forest and the - /// analysis are made only where such a load exists, and released after. - fn mark_uniform_loop_reads(&mut self, e: &Entry, m: &mut Meter) -> Result<(), Error> { - let Some(body) = e.module.func(e.func).and_then(|f| f.body.as_ref()) else { - return Ok(()); - }; - let mut candidates: Vec<(Root, usize)> = Vec::new(); - for (i, s) in self.slots.iter().enumerate() { - if self.read_only(s) { - grow(&mut candidates, 1, m)?; - candidates.push((Root::Param(s.param), i)); - } - } - if candidates.is_empty() { - return Ok(()); - } - let mut reads: Vec<(usize, BlockId, Value)> = Vec::new(); - let found = self.dynamic_reads(body, &candidates, &mut reads, m); - let marked = found.and_then(|()| match reads.is_empty() { - true => Ok(()), - false => self.uniform_reads_in_loops(e, body, &reads, m), - }); - m.release(vec_bytes(&reads).saturating_add(vec_bytes(&candidates))); - marked - } - - /// The loads of `body` through a pointer whose root set is one of `candidates`' roots alone, - /// at an offset that is not one constant, with the candidate's slot and the load's block. - fn dynamic_reads( - &self, - body: &Body, - candidates: &[(Root, usize)], - reads: &mut Vec<(usize, BlockId, Value)>, - m: &mut Meter, - ) -> Result<(), Error> { - for (b, block) in body.blocks.iter() { - for id in block.inst_ids() { - m.tick(1)?; - let Some(InstKind::Load { ptr, .. }) = body.insts.get(id).map(|i| &i.kind) else { - continue; - }; - let Some([root]) = self.roots_of(*ptr) else { - continue; - }; - let Some(&(_, slot)) = candidates.iter().find(|(r, _)| r == root) else { - continue; - }; - let constant = - matches!(self.offset(*ptr), Some(OffsetRange::Span { lo, hi }) if lo == hi); - if !constant { - grow(reads, 1, m)?; - reads.push((slot, b, *ptr)); - } - } - } - Ok(()) - } - - /// Mark the slots of `reads` that lie in a loop and whose pointer is uniform per instance. - fn uniform_reads_in_loops( - &mut self, - e: &Entry, - body: &Body, - reads: &[(usize, BlockId, Value)], - m: &mut Meter, - ) -> Result<(), Error> { - let loops = LoopForest::compute(&e.cfg, m)?; - let looped = reads.iter().any(|(_, b, _)| loops.innermost(*b).is_some()); - let result = match looped { - false => Ok(()), - true => Uniformity::per_instance(e, body, &loops, m).map(|u| { - for &(slot, b, ptr) in reads { - if loops.innermost(b).is_some() && u.is_uniform_value(e, ptr) { - if let Some(s) = self.slots.get_mut(slot) { - s.uniform_loop_reads = true; - } - } - } - m.release(u.ledger_bytes()); - }), - }; - m.release(loops.ledger_bytes()); - result - } - /// The slot index of buffer parameter `param` (a buffer table has one slot per accessed /// element instead; see [`MemoryPlan::slot_of_root`]). pub fn slot_of_param(&self, param: u32) -> Option { @@ -787,16 +671,6 @@ pub fn analyze_memory(e: &Entry, p: &DeviceProfile, m: &mut Meter) -> Result bool { - matches!(e.ep.stage, crate::air::abi::Stage::Kernel { .. }) - && p.workarounds() - .contains(&DriverWorkaround::UniformAddressStorageReadsSlow) -} - fn analyze(e: &Entry, p: &DeviceProfile, m: &mut Meter) -> Result { let layouts = TypeLayouts::new(&e.layout, e.module.types(), m)?; let prov = provenance::analyze(e, &layouts, m)?; @@ -910,9 +784,8 @@ impl Planner<'_> { } = self.reprs(&const_globals, &typed_allocas, &typed_shared, dynamic, m)?; let slot_roots = slot_roots(&slots, m)?; let const_index = const_index(&const_globals, m)?; - let (e, p) = (self.e, self.p); let Planner { prov, layouts, .. } = self; - let mut plan = MemoryPlan { + Ok(MemoryPlan { values: prov.values, layouts, repr, @@ -938,11 +811,7 @@ impl Planner<'_> { cells: prov.cells, abi: prov.abi, fragment_values, - }; - if marks_uniform_loop_reads(e, p) { - plan.mark_uniform_loop_reads(e, m)?; - } - Ok(plan) + }) } /// The bytes of private memory a thread holds where a driver backs it with scratch memory @@ -1129,7 +998,6 @@ impl Planner<'_> { atomic: eu.atomic, window: escaped_window(window::window(eu.extent, None, dynamic), eu), guest_base: eu.escapes || eu.cross_compare, - uniform_loop_reads: false, }); } continue; @@ -1156,7 +1024,6 @@ impl Planner<'_> { atomic: u.atomic, window: escaped_window(window::window(u.extent, arg.buffer_size, dynamic), &u), guest_base: u.escapes || u.cross_compare, - uniform_loop_reads: false, }); } Ok(slots) diff --git a/crates/metal2vulkan/src/memory/plan/tests.rs b/crates/metal2vulkan/src/memory/plan/tests.rs index f9f622699..245a5d079 100644 --- a/crates/metal2vulkan/src/memory/plan/tests.rs +++ b/crates/metal2vulkan/src/memory/plan/tests.rs @@ -1946,7 +1946,6 @@ fn spike_analysis_at_the_largest_row_size() { } mod gaps; -mod uniform_reads; /// A kernel whose argument buffer holds one sampled texture member at byte 8, loaded `n + 1` /// times; the loads are merged by a chain of `n` selects, `h{i+1} = select c, h{i}, l{i}`. Every diff --git a/crates/metal2vulkan/src/memory/plan/tests/uniform_reads.rs b/crates/metal2vulkan/src/memory/plan/tests/uniform_reads.rs deleted file mode 100644 index b1416dd1c..000000000 --- a/crates/metal2vulkan/src/memory/plan/tests/uniform_reads.rs +++ /dev/null @@ -1,263 +0,0 @@ -//! L0 tests: the read-only test ([`MemoryPlan::read_only`]) and which read-only slots the function -//! reads in a loop at an offset every thread executing the read holds alike -//! ([`SlotPlan::uniform_loop_reads`]), which only a kernel on a profile that takes -//! `DriverWorkaround::UniformAddressStorageReadsSlow` asks: the Iris Xe RPL-P's, against which -//! these kernels are planned, while `moltenvk-m3`'s plan marks none. - -use super::*; -use crate::air::abi::Builtin; -use crate::air::ir::BinOp; - -/// `[[buffer(index)]]` in device space, declared `air.read` ([`buffer`] declares `air.read_write`). -fn read_buffer(index: u32) -> ParamRole { - ParamRole::Buffer(BufferArg { - location: slot(index), - access: Access::Read, - space: AddrSpace::Device, - buffer_size: None, - layout: None, - raster_order_group: None, - }) -} - -/// A `uint` `[[thread_position_in_grid]]` parameter. -fn position(k: &mut Kernel) { - let i32t = k.mb.int(32); - k.params.push(i32t); - k.roles - .push(ParamRole::Builtin(Builtin::ThreadPositionInGrid)); -} - -/// The plan of `e` on the committed profile that takes the workaround. -fn on_iris(e: &Entry) -> MemoryPlan { - let iris = profile("intel-irisxe-rplp-anv", DevicePolicy::default()).expect("iris"); - plan(e, &iris).expect("analyze") -} - -fn uniform_loop_reads(p: &MemoryPlan, param: u32) -> bool { - p.slots - .iter() - .find(|s| s.param == param) - .expect("slot") - .uniform_loop_reads -} - -fn read_only(p: &MemoryPlan, param: u32) -> bool { - p.read_only(p.slots.iter().find(|s| s.param == param).expect("slot")) -} - -/// The instruction pushed `n` after instruction `v`: a forward reference (the builder numbers -/// instructions in push order, void ones included). -fn after(v: Value, n: u32) -> Value { - match v { - Value::Inst(i) => Value::Inst(InstId::new(i.raw() + n)), - other => panic!("not an instruction: {other:?}"), - } -} - -fn icmp(fb: &mut FunctionBuilder<'_>, pred: IntPredicate, a: Value, b: Value) -> Value { - let i1 = fb.module().int(1); - fb.push(i1, InstKind::ICmp { pred, a, b }) -} - -fn phi(fb: &mut FunctionBuilder<'_>, ty: TypeId, incoming: &[(Value, BlockId)]) -> Value { - fb.push( - ty, - InstKind::Phi { - incoming: incoming.into(), - fmf: FastMath::NONE, - }, - ) -} - -/// A convolution's tap loop: each thread sums `src[x]` times `weights[i]` while its own -/// `x = gid + i` stays below its own bound, so threads leave the loop after different -/// iterations. The counter `i` starts at 0 and steps by 1, so the threads in one iteration read -/// one weight: the weights' slot reads are uniform in a loop. The source's are at a per-thread -/// offset, and the output is written. -#[test] -fn a_tap_loop_reads_its_weights_uniformly_and_its_source_per_thread() { - let mut k = Kernel::new(); - k.param(AddrSpace::Device, read_buffer(0)); - k.param(AddrSpace::Device, read_buffer(1)); - k.param(AddrSpace::Device, buffer(2, AddrSpace::Device, None)); - position(&mut k); - let e = k.build(|fb| { - let i32t = fb.module().int(32); - let f32t = fb.module().float(); - let zero = fb.module().const_int(i32t, 0); - let one = fb.module().const_int(i32t, 1); - let eight = fb.module().const_int(i32t, 8); - let entry = BlockId::new(0); - let (head, exit) = (fb.block(), fb.block()); - let gid = fb.arg(3); - let end = fb.bin(BinOp::Add, gid, eight); - fb.br(head); - fb.switch_to(head); - // `end`, the `br`, the phi, then its back-edge value. - let i = phi(fb, i32t, &[(zero, entry), (after(end, 3), head)]); - let inc = fb.bin(BinOp::Add, i, one); - assert_eq!(inc, after(end, 3)); - let x = fb.bin(BinOp::Add, gid, i); - let at_weight = gep(fb, f32t, fb.arg(0), &[i]); - let w = load(fb, f32t, at_weight); - let at_source = gep(fb, f32t, fb.arg(1), &[x]); - let s = load(fb, f32t, at_source); - let c = icmp(fb, IntPredicate::Slt, x, end); - fb.cond_br(c, head, exit); - fb.switch_to(exit); - let at_out = gep(fb, f32t, fb.arg(2), &[gid]); - store(fb, s, at_out); - store(fb, w, at_out); - fb.ret(None); - }); - let plan = on_iris(&e); - assert!(read_only(&plan, 0) && read_only(&plan, 1)); - assert!(!read_only(&plan, 2)); - assert!(uniform_loop_reads(&plan, 0), "the weights at the counter"); - assert!( - !uniform_loop_reads(&ok(&e), 0), - "a profile without the workaround asks nothing" - ); - assert!(!uniform_loop_reads(&plan, 1), "the source at gid + i"); - assert!(!uniform_loop_reads(&plan, 2), "the written output"); -} - -/// An index merged at the join of a branch on the thread's position is per thread, though both -/// its incoming values are constants; the same kernel whose branch every thread takes alike (a -/// constant condition) reads uniformly. The loop's own exit is uniform in both. -#[test] -fn an_index_merged_at_a_divergent_join_is_not_uniform() { - for (divergent, want) in [(true, false), (false, true)] { - let mut k = Kernel::new(); - k.param(AddrSpace::Device, read_buffer(0)); - k.param(AddrSpace::Device, buffer(1, AddrSpace::Device, None)); - position(&mut k); - let e = k.build(|fb| { - let i32t = fb.module().int(32); - let f32t = fb.module().float(); - let zero = fb.module().const_int(i32t, 0); - let one = fb.module().const_int(i32t, 1); - let two = fb.module().const_int(i32t, 2); - let four = fb.module().const_int(i32t, 4); - let eight = fb.module().const_int(i32t, 8); - let (a, b, merge, head, exit) = - (fb.block(), fb.block(), fb.block(), fb.block(), fb.block()); - let tested = match divergent { - true => fb.arg(2), - false => zero, - }; - let c0 = icmp(fb, IntPredicate::Ult, tested, four); - fb.cond_br(c0, a, b); - fb.switch_to(a); - fb.br(merge); - fb.switch_to(b); - fb.br(merge); - fb.switch_to(merge); - let k = phi(fb, i32t, &[(one, a), (two, b)]); - fb.br(head); - fb.switch_to(head); - // `k`, the `br`, the phi, then its back-edge value. - let i = phi(fb, i32t, &[(zero, merge), (after(k, 3), head)]); - let inc = fb.bin(BinOp::Add, i, one); - assert_eq!(inc, after(k, 3)); - let j = fb.bin(BinOp::Add, i, k); - let at = gep(fb, f32t, fb.arg(0), &[j]); - let w = load(fb, f32t, at); - let c = icmp(fb, IntPredicate::Ult, inc, eight); - fb.cond_br(c, head, exit); - fb.switch_to(exit); - store(fb, w, fb.arg(1)); - fb.ret(None); - }); - let plan = on_iris(&e); - assert_eq!( - uniform_loop_reads(&plan, 0), - want, - "divergent branch: {divergent}" - ); - } -} - -/// A read at a uniform offset outside any loop is not a loop read, and a slot read at one -/// constant offset in a loop is not either. -#[test] -fn only_dynamic_reads_in_loops_count() { - let mut k = Kernel::new(); - k.param(AddrSpace::Device, read_buffer(0)); - k.param(AddrSpace::Device, read_buffer(1)); - k.param(AddrSpace::Device, buffer(2, AddrSpace::Device, None)); - let e = k.build(|fb| { - let i32t = fb.module().int(32); - let f32t = fb.module().float(); - let zero = fb.module().const_int(i32t, 0); - let one = fb.module().const_int(i32t, 1); - let three = fb.module().const_int(i32t, 3); - let eight = fb.module().const_int(i32t, 8); - let entry = BlockId::new(0); - let (head, exit) = (fb.block(), fb.block()); - // Slot 0 outside the loop at a uniform but not constant offset. - let n = load(fb, i32t, fb.arg(1)); - let n = fb.bin(BinOp::And, n, zero); - let at_first = gep(fb, f32t, fb.arg(0), &[n]); - let first = load(fb, f32t, at_first); - fb.br(head); - fb.switch_to(head); - // `first`, the `br`, the phi, then its back-edge value. - let i = phi(fb, i32t, &[(zero, entry), (after(first, 3), head)]); - let inc = fb.bin(BinOp::Add, i, one); - assert_eq!(inc, after(first, 3)); - // Slot 1 in the loop at one constant offset. - let at_fixed = gep(fb, f32t, fb.arg(1), &[three]); - let fixed = load(fb, f32t, at_fixed); - let c = icmp(fb, IntPredicate::Ult, inc, eight); - fb.cond_br(c, head, exit); - fb.switch_to(exit); - store(fb, first, fb.arg(2)); - store(fb, fixed, fb.arg(2)); - fb.ret(None); - }); - let plan = on_iris(&e); - assert!(read_only(&plan, 0) && read_only(&plan, 1)); - assert!(!uniform_loop_reads(&plan, 0), "outside the loop"); - assert!(!uniform_loop_reads(&plan, 1), "one constant offset"); -} - -/// The read-only test: a slot declared `air.read_write` that is only read is not, nor one -/// declared `air.read` that is written, nor any slot of a function where a buffer pointer has a -/// dynamic root (a pointer loaded from memory may reach the slot's memory). -#[test] -fn read_only_needs_the_declaration_the_accesses_and_no_dynamic_root() { - let mut k = Kernel::new(); - k.param(AddrSpace::Device, read_buffer(0)); - k.param(AddrSpace::Device, buffer(1, AddrSpace::Device, None)); - k.param(AddrSpace::Device, read_buffer(2)); - let e = k.build(|fb| { - let i32t = fb.module().int(32); - let v = load(fb, i32t, fb.arg(0)); - let u = load(fb, i32t, fb.arg(1)); - let sum = fb.bin(BinOp::Add, v, u); - store(fb, sum, fb.arg(2)); - fb.ret(None); - }); - let plan = ok(&e); - assert!(!plan.needs.dynamic_roots); - assert!(read_only(&plan, 0), "declared and accessed read only"); - assert!(!read_only(&plan, 1), "declared read_write"); - assert!(!read_only(&plan, 2), "declared read, written"); - - let mut k = Kernel::new(); - k.param(AddrSpace::Device, read_buffer(0)); - k.param(AddrSpace::Device, buffer(1, AddrSpace::Device, None)); - let e = k.build(|fb| { - let i32t = fb.module().int(32); - let ptr = fb.module().ptr(AddrSpace::Device); - let q = load(fb, ptr, fb.arg(0)); - let v = load(fb, i32t, q); - store(fb, v, fb.arg(1)); - fb.ret(None); - }); - let plan = ok(&e); - assert!(plan.needs.dynamic_roots); - assert!(!read_only(&plan, 0), "a dynamic root may reach it"); -} diff --git a/crates/metal2vulkan/src/pipeline/facts.rs b/crates/metal2vulkan/src/pipeline/facts.rs index c5b7262f5..40afaaf05 100644 --- a/crates/metal2vulkan/src/pipeline/facts.rs +++ b/crates/metal2vulkan/src/pipeline/facts.rs @@ -110,12 +110,9 @@ pub enum RuntimeFact { /// whatever the bind's, and records nothing. StageInStride { layout: u32 }, /// A read-only slot that Profile F's per-stage storage-buffer fallback may read through a - /// uniform view, or that a profile taking `DriverWorkaround::UniformAddressStorageReadsSlow` - /// reads through one (a kernel's slot read in a loop at a per-instance uniform offset, whose - /// memory no write of the dispatch reaches), whose window does not bound its descriptor range - /// within `maxUniformBufferRange` (a `Whole` window, or a longer `Bounded` one): the view is - /// exact only where the range the shape binds fits. `choice` states what this compile made of - /// it. + /// uniform view, whose window does not bound its descriptor range within + /// `maxUniformBufferRange` (a `Whole` window, or a longer `Bounded` one): the view is exact + /// only where the range the shape binds fits. `choice` states what this compile made of it. /// A plan whose shape does not prove the fit for a `Viewed` slot asks for the variant that /// keeps every such slot a storage view (`VariantKey::storage_view_slots`); instantiation /// refuses a range above the limit (`BindError::DescriptorRangeExceeded`). diff --git a/crates/metal2vulkan/src/tests/engine_loop_uniform_views.rs b/crates/metal2vulkan/src/tests/engine_loop_uniform_views.rs deleted file mode 100644 index 702baf715..000000000 --- a/crates/metal2vulkan/src/tests/engine_loop_uniform_views.rs +++ /dev/null @@ -1,396 +0,0 @@ -//! A kernel's read-only slot read in a loop at a per-instance uniform offset, whose memory no -//! write of the dispatch reaches, is a uniform view on a profile that takes -//! `DriverWorkaround::UniformAddressStorageReadsSlow` (the Iris Xe RPL-P under ANV), and a storage -//! view everywhere else (`lower::access::loop_uniform_views`). -//! -//! The kernel is a four-tap convolution of our own: `out[gid] = sum(weights[i] * source[gid + -//! i])`, the counter `i` running from 0 to 3 alike in every thread. Its weights are read at the -//! counter, its source at a per-thread offset, and its output written. Each test pins one part: -//! the form and the set-0 descriptor type on the profile that takes the workaround and on the one -//! of the same driver and capabilities that does not (the UHD Graphics 770 of RPL-S); the two -//! proofs the uniform view needs from the function (an unaliased argument, nothing writing it); -//! the variant a shape binding more than `maxUniformBufferRange` asks for; and, on the CPU -//! interpreter, the same bytes through either view. -//! -//! `llvm-as` assembles the kernel; without it the tests skip visibly. - -use std::collections::{BTreeMap, BTreeSet}; -use std::path::Path; - -use crate::bind::{BindState, BoundBuffer, DescriptorWrite, StageTable}; -use crate::budget::Budget; -use crate::device::{Device, DeviceDescription, DevicePolicy, DriverWorkaround}; -use crate::library::Library; -use crate::pipeline::interface::{BufferForm, DescriptorView, SlotInterface}; -use crate::pipeline::layout::BindingSource; -use crate::pipeline::sym::{Axis, ResourceKind, ResourceSlot, SlotClass, SlotRef, SpecKey, Stage}; -use crate::pipeline::testing::{llvm_assemble, typed_module_with, AssembleError, Scratch}; -use crate::pipeline::{ - ComputePipeline, ComputePipelineDescriptor, FunctionDescriptor, LoweringInputs, RuntimeFact, - StageSource, UniformViewChoice, -}; -use crate::spirv::interp::{run, Buffer, Config, Resources}; - -/// The committed profile that takes the workaround, and one of the same driver and capabilities -/// that does not. -const IRIS: &str = "intel-irisxe-rplp-anv"; -const RPLS: &str = "intel-uhd770-rpls-anv"; - -const ENTRY: &str = "tap_loop"; - -/// The kernel, its weights argument declared with `weights_attrs` and `weights_access`, its exit -/// running `exit_extra` before its store. -fn kernel(weights_attrs: &str, weights_access: &str, exit_extra: &str) -> String { - format!( - r#"target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32" -target triple = "air64_v28-apple-macosx26.0.0" - -define void @tap_loop(ptr addrspace(1) noundef {weights_attrs} %0, ptr addrspace(1) noundef readonly "air-buffer-no-alias" %1, ptr addrspace(1) noundef "air-buffer-no-alias" %2, i32 noundef %3) {{ -entry: - br label %loop - -loop: - %i = phi i32 [ 0, %entry ], [ %next, %loop ] - %acc = phi float [ 0.0, %entry ], [ %sum, %loop ] - %iz = zext i32 %i to i64 - %wp = getelementptr inbounds float, ptr addrspace(1) %0, i64 %iz - %w = load float, ptr addrspace(1) %wp, align 4 - %x = add i32 %3, %i - %xz = zext i32 %x to i64 - %sp = getelementptr inbounds float, ptr addrspace(1) %1, i64 %xz - %s = load float, ptr addrspace(1) %sp, align 4 - %m = fmul float %w, %s - %sum = fadd float %acc, %m - %next = add nuw nsw i32 %i, 1 - %done = icmp eq i32 %next, 4 - br i1 %done, label %exit, label %loop - -exit: -{exit_extra} %gz = zext i32 %3 to i64 - %dp = getelementptr inbounds float, ptr addrspace(1) %2, i64 %gz - store float %sum, ptr addrspace(1) %dp, align 4 - ret void -}} - -!air.kernel = !{{!9}} -!air.version = !{{!17}} -!air.language_version = !{{!18}} -!9 = !{{ptr @tap_loop, !10, !11}} -!10 = !{{}} -!11 = !{{!12, !13, !14, !15}} -!12 = !{{i32 0, !"air.buffer", !"air.location_index", i32 0, i32 1, !"{weights_access}", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"float", !"air.arg_name", !"weights"}} -!13 = !{{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"float", !"air.arg_name", !"source"}} -!14 = !{{i32 2, !"air.buffer", !"air.location_index", i32 2, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"float", !"air.arg_name", !"out"}} -!15 = !{{i32 3, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"gid"}} -!17 = !{{i32 2, i32 8, i32 0}} -!18 = !{{!"Metal", i32 4, i32 0, i32 0}} -"# - ) -} - -/// The kernel as the tests read it: its weights an unaliased `device const float *`. -fn tap_loop() -> String { - kernel(r#"readonly "air-buffer-no-alias""#, "air.read", "") -} - -/// `text` assembled through a scratch file this test owns and removes. -fn assemble(name: &str, text: &str) -> Option> { - let scratch = Scratch::new(&format!("m2v-loop-uniform-views-{name}")); - let ll = scratch.path().join(format!("{name}.ll")); - std::fs::write(&ll, text).expect("write"); - match llvm_assemble(&ll) { - Ok(b) => Some(b), - Err(AssembleError::Missing(why)) => { - eprintln!("SKIPPED: {why}"); - None - } - Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected {name}: {why}"), - } -} - -fn device(stem: &str) -> Device { - let path = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/profiles") - .join(format!("{stem}.json")); - let text = std::fs::read_to_string(path).expect("profile"); - let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - Device::new(desc, DevicePolicy::default()).expect("device") -} - -fn sref(index: u32) -> SlotRef { - SlotRef { - stage: Stage::Kernel, - class: SlotClass::Buffer, - index, - } -} - -/// The kernel's pipeline on `dev`, compiled under `inputs`. -fn pipeline(dev: &Device, bc: &[u8], inputs: &LoweringInputs) -> ComputePipeline { - let lib = Library::from_air(bc).expect("library"); - let f = lib.function(ENTRY).expect("function"); - let compiled = dev - .compile_function(&FunctionDescriptor::new(f), inputs, &Budget::standard()) - .expect("compile"); - dev.compile_compute_pipeline( - &ComputePipelineDescriptor::new(StageSource::Compiled(compiled)), - &Budget::standard(), - ) - .expect("pipeline") -} - -fn form(p: &ComputePipeline, index: u32) -> BufferForm { - match p.interface.slots.get(&sref(index)) { - Some(SlotInterface::Buffer(b)) => b.form, - other => panic!("slot {index}: {other:?}"), - } -} - -fn has_fact(p: &ComputePipeline, fact: RuntimeFact) -> bool { - p.dependencies.iter().any(|d| d.fact == fact) -} - -/// A bound buffer of `length` bytes at a GPU address of its own. -fn buf(index: u32, length: u64) -> BoundBuffer { - BoundBuffer::Buffer { - length, - offset: 0, - gpu_address: 0x10_0000_0000 + u64::from(index) * 0x1_0000_0000, - device_address: None, - attribute_stride: None, - } -} - -/// The kernel's bind state: its weights `weights` bytes long, its source and output 1 KiB. -fn state(weights: u64) -> BindState { - let mut t = StageTable::default(); - t.buffers.insert(0, buf(0, weights)); - t.buffers.insert(1, buf(1, 1024)); - t.buffers.insert(2, buf(2, 1024)); - let mut state = BindState::default(); - state.stages.insert(Stage::Kernel, t); - state -} - -/// The set-0 descriptor type the plan of `p` for `shape` writes at buffer slot `index`. -fn set0_type( - p: &ComputePipeline, - dev: &Device, - s: &BindState, - index: u32, -) -> crate::vk::DescriptorType { - let plan = p.plan(dev, &s.shape()).expect("plan"); - let source = |write: &DescriptorWrite| { - (p.layout.sets.iter()) - .filter(|set| set.set == write.set) - .flat_map(|set| &set.bindings) - .find(|b| b.binding == write.binding) - .map(|b| b.source) - }; - (plan.descriptors.iter()) - .find(|w| w.set == 0 && source(w) == Some(BindingSource::Buffer(sref(index)))) - .map(|w| w.ty) - .unwrap_or_else(|| panic!("no set-0 write of slot {index}")) -} - -/// On the Iris the weights are a uniform view whose set-0 binding is a `UNIFORM_BUFFER`, its -/// window (an unsized pointer read at the counter) unbounded, so it states its range fact as -/// `Viewed` and no `BufferRangeLimit`; the source, read at a per-thread offset, and the written -/// output stay storage views. On the RPL-S, the same driver and capabilities without the -/// workaround, the weights are a storage view and a `STORAGE_BUFFER`, as before. -#[test] -fn a_loop_uniform_slot_is_a_uniform_view_where_the_profile_takes_the_workaround() { - let Some(bc) = assemble("tap_loop", &tap_loop()) else { - return; - }; - let uniform = BufferForm::Descriptor(DescriptorView::UniformWords); - let storage = BufferForm::Descriptor(DescriptorView::Storage); - let small = state(16); - let iris = device(IRIS); - assert!(iris - .profile() - .workarounds() - .contains(&DriverWorkaround::UniformAddressStorageReadsSlow)); - let p = pipeline(&iris, &bc, &LoweringInputs::new()); - assert_eq!( - [form(&p, 0), form(&p, 1), form(&p, 2)], - [uniform, storage, storage], - "{IRIS}" - ); - assert!(has_fact( - &p, - RuntimeFact::UniformViewRange { - slot: sref(0), - choice: UniformViewChoice::Viewed, - } - )); - assert!(!has_fact( - &p, - RuntimeFact::BufferRangeLimit { slot: sref(0) } - )); - assert_eq!( - set0_type(&p, &iris, &small, 0), - crate::vk::DescriptorType::UNIFORM_BUFFER - ); - assert_eq!( - set0_type(&p, &iris, &small, 1), - crate::vk::DescriptorType::STORAGE_BUFFER - ); - - let rpls = device(RPLS); - assert!(!rpls - .profile() - .workarounds() - .contains(&DriverWorkaround::UniformAddressStorageReadsSlow)); - let p = pipeline(&rpls, &bc, &LoweringInputs::new()); - assert_eq!( - [form(&p, 0), form(&p, 1), form(&p, 2)], - [storage, storage, storage], - "{RPLS}" - ); - assert!(!p - .dependencies - .iter() - .any(|d| matches!(d.fact, RuntimeFact::UniformViewRange { .. }))); - assert_eq!( - set0_type(&p, &rpls, &small, 0), - crate::vk::DescriptorType::STORAGE_BUFFER - ); -} - -/// The uniform view needs both of the function's proofs that no write of the dispatch reaches -/// the weights: on the Iris, weights whose argument the AIR does not declare unaliased (no -/// `air-buffer-no-alias`), and weights the kernel also writes, stay storage views. -#[test] -fn a_loop_uniform_view_needs_an_unaliased_argument_nothing_writes() { - let iris = device(IRIS); - let storage = BufferForm::Descriptor(DescriptorView::Storage); - let cases = [ - ("aliased", kernel("readonly", "air.read", "")), - ( - "written", - kernel( - r#""air-buffer-no-alias""#, - "air.read_write", - " store float %sum, ptr addrspace(1) %0, align 4\n", - ), - ), - ]; - for (what, text) in cases { - let Some(bc) = assemble(what, &text) else { - return; - }; - let p = pipeline(&iris, &bc, &LoweringInputs::new()); - assert_eq!(form(&p, 0), storage, "{what}"); - assert!( - !has_fact( - &p, - RuntimeFact::UniformViewRange { - slot: sref(0), - choice: UniformViewChoice::Viewed, - } - ), - "{what}" - ); - } -} - -/// A shape binding the weights a buffer whose length class does not fit `maxUniformBufferRange` -/// (1 GiB on the Iris) asks for the variant that keeps them a storage view -/// (`VariantKey::storage_view_slots`); a small one asks for none. The variant's weights are a -/// storage view stated `Kept`, and its plan for the same shape states the same key. -#[test] -fn a_large_buffer_at_a_loop_uniform_view_asks_for_its_storage_variant() { - let Some(bc) = assemble("tap_loop_large", &tap_loop()) else { - return; - }; - let iris = device(IRIS); - let base = pipeline(&iris, &bc, &LoweringInputs::new()); - let small = base.plan(&iris, &state(16).shape()).expect("plan"); - assert!(small.variant.is_empty(), "small weights need no variant"); - let large = state(2 << 30); - let plan = base.plan(&iris, &large.shape()).expect("plan"); - assert_eq!(plan.variant.storage_view_slots, BTreeSet::from([sref(0)])); - let inputs = plan.variant.lowering_inputs(Stage::Kernel); - let variant = pipeline(&iris, &bc, &inputs); - assert_eq!( - form(&variant, 0), - BufferForm::Descriptor(DescriptorView::Storage) - ); - assert!(has_fact( - &variant, - RuntimeFact::UniformViewRange { - slot: sref(0), - choice: UniformViewChoice::Kept, - } - )); - let again = variant.plan(&iris, &large.shape()).expect("variant plan"); - assert_eq!(again.variant, plan.variant, "a fixed point"); -} - -/// On the CPU interpreter, eight threads of the Iris's base module (the weights' uniform view) -/// and of its storage-view variant write the same output, the convolution's own. -#[test] -fn a_loop_uniform_view_reads_the_bytes_the_storage_view_does() { - let Some(bc) = assemble("tap_loop_bytes", &tap_loop()) else { - return; - }; - let iris = device(IRIS); - let p = iris.profile(); - let weights = [0.5f32, -1.25, 2.0, 0.75]; - let source: Vec = (0..16).map(|k| k as f32 * 0.5 - 3.0).collect(); - let want: Vec = (0..8) - .map(|g| (0..4).fold(0.0f32, |acc, i| acc + weights[i] * source[g + i])) - .collect(); - let bytes = |v: &[f32]| v.iter().flat_map(|f| f.to_le_bytes()).collect::>(); - let kslot = |index| ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Buffer, - index, - }; - let mut spec = BTreeMap::new(); - spec.insert(SpecKey::LocalSize(Axis::X), 8); - spec.insert(SpecKey::LocalSize(Axis::Y), 1); - spec.insert(SpecKey::LocalSize(Axis::Z), 1); - spec.insert(SpecKey::FlatLocalSize, 8); - let mut variant = LoweringInputs::new(); - variant.storage_view_slots.insert(sref(0)); - let mut outs = Vec::new(); - for (what, inputs, view) in [ - ("base", LoweringInputs::new(), "uniform"), - ("variant", variant, "storage"), - ] { - let (_, m) = typed_module_with(&bc, ENTRY, p, &inputs).expect("module"); - let res = Resources { - buffers: vec![ - Buffer { - slot: Some(kslot(0)), - address: None, - bytes: bytes(&weights), - }, - Buffer { - slot: Some(kslot(1)), - address: None, - bytes: bytes(&source), - }, - Buffer { - slot: Some(kslot(2)), - address: None, - bytes: vec![0xEE; 32], - }, - ], - push: vec![0; 128], - spec: spec.clone(), - }; - let out = run(&m, &Config::default(), res).unwrap_or_else(|e| panic!("{what}: {e:?}")); - let got: Vec = out.buffers[2] - .as_chunks::<4>() - .0 - .iter() - .map(|w| f32::from_le_bytes(*w)) - .collect(); - assert_eq!(got, want, "{what}: the weights through a {view} view"); - outs.push(out.buffers[2].clone()); - } - assert_eq!(outs[0], outs[1], "the two views' bytes"); -} diff --git a/crates/metal2vulkan/src/tests/mod.rs b/crates/metal2vulkan/src/tests/mod.rs index 462edcfc1..d68706601 100644 --- a/crates/metal2vulkan/src/tests/mod.rs +++ b/crates/metal2vulkan/src/tests/mod.rs @@ -96,7 +96,6 @@ mod engine_line_band; mod engine_link; mod engine_linked_signatures; mod engine_linking; -mod engine_loop_uniform_views; mod engine_loop_unrolling; mod engine_matmul2d; mod engine_mesh; diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 515dcd759..19f6a2d0e 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -13952,7 +13952,6 @@ variant metal2vulkan::device::DriverWorkaround::PushReadsLengthenThreadPayload P variant metal2vulkan::device::DriverWorkaround::RegisterAllocatorOverflowsLargeModules RegisterAllocatorOverflowsLargeModules variant metal2vulkan::device::DriverWorkaround::SerializedStageWrapsLargeModules SerializedStageWrapsLargeModules variant metal2vulkan::device::DriverWorkaround::TessellatorNotMetals TessellatorNotMetals -variant metal2vulkan::device::DriverWorkaround::UniformAddressStorageReadsSlow UniformAddressStorageReadsSlow variant metal2vulkan::device::DriverWorkaround::VertexGroupingNotApples VertexGroupingNotApples variant metal2vulkan::device::Exposure::Core Core(ApiVersion) variant metal2vulkan::device::Exposure::Extension Extension(&'static [VkExtension]) diff --git a/docs/API.md b/docs/API.md index 090d5f75c..21d195bfa 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1497,19 +1497,6 @@ for dependency in &pipeline.dependencies { bytes ran in 161.8 us a dispatch with the bytes' uniform view read at its bind offset, and in 142.8 us with it read at its residual. Elsewhere no storage view declares the key, and `zero_offset_views` changes nothing. -- On a profile that takes `DriverWorkaround::UniformAddressStorageReadsSlow` (ANV on the Iris Xe - RPL-P, where a convolution's weights read through a storage view in its tap loop took 316.3 us - per tap and through a uniform view 249.0), a kernel's read-only buffer slot that the function - reads in a loop at an offset every thread executing the read holds alike, and whose memory - nothing in the function writes (an argument the AIR declares unaliased, `air-buffer-no-alias`, - that no store, atomic, volatile or coherent access reaches), is a uniform view - (`DescriptorView::UniformWords` or `UniformVec4`, a `UNIFORM_BUFFER` binding of set 0) where it - would be a storage view: sized to its window, or to `maxUniformBufferRange` where the window - does not bound it. Such a slot then lists `RuntimeFact::UniformViewRange` among the - dependencies, and a plan whose shape binds it a buffer whose length class does not fit - `maxUniformBufferRange` names the variant that keeps it a storage view - (`VariantKey::storage_view_slots`): compile that variant before binding, as for any variant. - The two views read the same bytes. Elsewhere such a slot is a storage view, as before. - A bound buffer's length enters its shape only as a length class (`bind::length_class`), which a plan compares with the device's `maxUniformBufferRange` and `maxStorageBufferRange` alone (whether every range of the buffer fits each). Set each table's