diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index cf0005c8b..8d4806dcb 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -4740,8 +4740,8 @@ cache is answered compile-required on both. emulated SIMD groups (site `SimdGroups`), and for a kernel that observes its threadgroup partition and whose partial-threadgroups variant the translator refuses, the site naming why: the vote word below (`VoteWord`), a structure of the kernel's the variant does not take - (`Structure`, its `PartialThreadgroupsCause`: compute derivatives, an imageblock slice write - every invocation shares, a tile function), or another refusal of the variant's (`Translator`). + (`Structure`, its `PartialThreadgroupsCause`: compute derivatives or a tile function), or another + refusal of the variant's (`Translator`). The cache directory keeps the site with the refusal. It refuses the variant of a kernel whose barriers in a loop need a vote word that does not fit beside its threadgroup memory in diff --git a/crates/metal2vulkan-runtime/src/cache.rs b/crates/metal2vulkan-runtime/src/cache.rs index 15e3d7d8b..859ea9c19 100644 --- a/crates/metal2vulkan-runtime/src/cache.rs +++ b/crates/metal2vulkan-runtime/src/cache.rs @@ -191,7 +191,7 @@ const REFUSED: &[u8] = b"m2v-refused"; /// ([`REFUSED_VOTE`]), one for each structure of the kernel's the translator names, and any /// other refusal's ([`REFUSED`]). The markers are bytes no lowering encodes to, no two alike nor /// [`OBSERVES`], and none a file cut short. -pub(crate) const REFUSALS: [(VariantRefusal, &[u8]); 6] = [ +pub(crate) const REFUSALS: [(VariantRefusal, &[u8]); 5] = [ (VariantRefusal::VoteWord, REFUSED_VOTE), ( VariantRefusal::Structure(PartialThreadgroupsCause::ComputeDerivatives), @@ -201,10 +201,6 @@ pub(crate) const REFUSALS: [(VariantRefusal, &[u8]); 6] = [ VariantRefusal::Structure(PartialThreadgroupsCause::OtherForm), b"m2v-refused-form", ), - ( - VariantRefusal::Structure(PartialThreadgroupsCause::SharedSliceWrite), - b"m2v-refused-slice", - ), ( VariantRefusal::Structure(PartialThreadgroupsCause::TileFunction), b"m2v-refused-tile", @@ -308,6 +304,9 @@ pub(crate) struct Store { /// The times the store read the state file outside its lock. #[cfg(test)] pub(crate) state_reads: AtomicUsize, + /// The times a lookup opened, or tried to open, a file under a generation. + #[cfg(test)] + pub(crate) file_opens: AtomicUsize, } impl Store { @@ -348,6 +347,8 @@ impl Store { listings: AtomicUsize::new(0), #[cfg(test)] state_reads: AtomicUsize::new(0), + #[cfg(test)] + file_opens: AtomicUsize::new(0), }); store.meet(); if let Some(state) = store.current() { @@ -413,15 +414,33 @@ impl Store { file: &str, decode: impl FnOnce(&[u8]) -> Option, ) -> Option { - self.lookup(file, None, decode, true) + self.lookup(file, |_| true, decode, true) } /// Whether the directory holds `bytes` as `file`, reading it only where its length is /// theirs; a file that differs stays. pub(crate) fn holds(self: &Arc, file: &str, bytes: &[u8]) -> bool { - let len = Some(bytes.len() as u64); - self.lookup(file, len, |held| (held == bytes).then_some(()), false) - .is_some() + self.holds_one(file, &[((), bytes)]).is_some() + } + + /// Which of `markers` the directory holds as `file`, by the tag beside it: one lookup of the + /// file, read only where its length is a marker's; a file that differs stays. + pub(crate) fn holds_one( + self: &Arc, + file: &str, + markers: &[(T, &[u8])], + ) -> Option { + let fits = |held: u64| { + markers + .iter() + .any(|&(_, marker)| marker.len() as u64 == held) + }; + let find = |held: &[u8]| { + (markers.iter()) + .find(|&&(_, marker)| marker == held) + .map(|&(tag, _)| tag) + }; + self.lookup(file, fits, find, false) } /// Keeps `bytes` as `file` in young. False where they were not written: more than half the @@ -482,7 +501,7 @@ impl Store { fn lookup( self: &Arc, file: &str, - len: Option, + fits: impl Fn(u64) -> bool, decode: impl FnOnce(&[u8]) -> Option, torn: bool, ) -> Option { @@ -490,7 +509,9 @@ impl Store { let mut decode = Some(decode); for (number, old) in [(young, false), (young.saturating_sub(1), true)] { let path = self.generation(number).join(file); - let bytes = match read_whole(&path, len) { + #[cfg(test)] + self.file_opens.fetch_add(1, Relaxed); + let bytes = match read_fitting(&path, &fits) { Err(error) if error.kind() == ErrorKind::NotFound => continue, Ok(Some(bytes)) => bytes, Ok(None) | Err(_) => return None, @@ -797,9 +818,15 @@ fn write_at(file: &File, buf: &[u8], at: u64) -> io::Result<()> { /// The bytes of the file at `path`, where they are `len` long (any length with none); `None` /// where they are not. pub(crate) fn read_whole(path: &Path, len: Option) -> io::Result>> { + read_fitting(path, |held| len.is_none_or(|len| len == held)) +} + +/// The bytes of the file at `path` where `fits` takes its length; `None` where it does not, the +/// file unread. +fn read_fitting(path: &Path, fits: impl Fn(u64) -> bool) -> io::Result>> { let mut opened = File::open(path)?; let held = opened.metadata()?.len(); - if len.is_some_and(|len| len != held) { + if !fits(held) { return Ok(None); } let mut bytes = vec![0; usize::try_from(held).map_err(|_| ErrorKind::OutOfMemory)?]; @@ -1505,7 +1532,7 @@ impl Caches { self.header.get().copied() } - fn translation_file(key: &[u8]) -> String { + pub(crate) fn translation_file(key: &[u8]) -> String { format!("{TRANSLATIONS}/{}", hex(key)) } @@ -1565,14 +1592,17 @@ impl Caches { } /// Why the translator refused the lowering of key digest `key` on a device before, where it - /// did. + /// did: one lookup of its translation file, read only where its length is a marker's + /// ([`REFUSALS`]). pub(crate) fn refused(&self, key: &[u8]) -> Option { let store = self.store.as_ref()?; - let file = Caches::translation_file(key); - REFUSALS - .iter() - .find(|&&(_, marker)| store.holds(&file, marker)) - .map(|&(why, _)| why) + store.holds_one(&Caches::translation_file(key), &REFUSALS) + } + + /// For the tests: the store on the cache directory, where there is one. + #[cfg(test)] + pub(crate) fn store_for_test(&self) -> Option<&Arc> { + self.store.as_ref() } /// Whether the translator answered on a device before that the kernel whose diff --git a/crates/metal2vulkan-runtime/src/error.rs b/crates/metal2vulkan-runtime/src/error.rs index bf3684bbd..a4771f2d0 100644 --- a/crates/metal2vulkan-runtime/src/error.rs +++ b/crates/metal2vulkan-runtime/src/error.rs @@ -2324,7 +2324,7 @@ pub enum PartialThreadgroupsSite { max: u32, }, /// The translator refused the variant for a structure of the kernel's that it names: compute - /// derivatives, an imageblock slice write every invocation shares, or a tile function. + /// derivatives or a tile function. Structure { /// The structure. cause: PartialThreadgroupsCause, diff --git a/crates/metal2vulkan-runtime/src/tests/cache.rs b/crates/metal2vulkan-runtime/src/tests/cache.rs index 6301fb5c3..d718d33ab 100644 --- a/crates/metal2vulkan-runtime/src/tests/cache.rs +++ b/crates/metal2vulkan-runtime/src/tests/cache.rs @@ -13,7 +13,7 @@ use crate::cache::{ blob_name, checksum, frame, prune_blobs, read_record, record_bytes, unframe, usable_header, - Caches, Lowerings, Pending, State, Store, Versions, BLOBS_KEPT, RECORD_LEN, + Caches, Lowerings, Pending, State, Store, Versions, BLOBS_KEPT, RECORD_LEN, REFUSALS, }; use crate::counters::Counters; use std::fs; @@ -756,6 +756,35 @@ fn a_torn_file_is_a_miss_and_is_removed() { assert!(store.generation(1).join(name(2)).exists()); } +/// A refusal of a partial-threadgroups variant is read back from its translation file in one +/// lookup, whichever marker it holds: one file opened in young, read once. A key with no file +/// tries each generation once, and a lowering of a marker's length is no refusal. +#[test] +fn a_variant_refusal_is_read_back_in_one_lookup_of_its_file() { + let scratch = Scratch::new("store-refused"); + let caches = Caches::new(Some(&scratch.0), 1000, &Counters::new()); + let writer = Store::open(scratch.0.clone(), 1000, Counters::new(), Versions::BUILT); + let store = caches.store_for_test().expect("a store"); + let opens = || store.file_opens.load(Relaxed); + for (n, &(why, marker)) in (0u8..).zip(REFUSALS.iter()) { + let key = [n; 32]; + assert!(writer.put(&Caches::translation_file(&key), marker)); + let before = opens(); + assert_eq!(caches.refused(&key), Some(why)); + assert_eq!(opens() - before, 1, "{why:?}"); + } + let before = opens(); + assert_eq!(caches.refused(&[0xee; 32]), None); + assert!( + opens() - before <= 2, + "{} opens for a missing file", + opens() - before + ); + let lowering = vec![0x5a; REFUSALS[0].1.len()]; + assert!(writer.put(&Caches::translation_file(&[0xdd; 32]), &lowering)); + assert_eq!(caches.refused(&[0xdd; 32]), None); +} + #[test] fn stores_on_one_directory_share_its_files_and_its_count() { let scratch = Scratch::new("store-share"); diff --git a/crates/metal2vulkan-runtime/src/tests/lowered.rs b/crates/metal2vulkan-runtime/src/tests/lowered.rs index 28d9abb7a..a997fd154 100644 --- a/crates/metal2vulkan-runtime/src/tests/lowered.rs +++ b/crates/metal2vulkan-runtime/src/tests/lowered.rs @@ -82,7 +82,6 @@ fn a_variant_refusal_keeps_the_translator_s_cause() { let structures = [ PartialThreadgroupsCause::ComputeDerivatives, PartialThreadgroupsCause::OtherForm, - PartialThreadgroupsCause::SharedSliceWrite, PartialThreadgroupsCause::TileFunction, ]; let mut kept = vec![VariantRefusal::VoteWord, VariantRefusal::Translator]; diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 05fd26ad7..c7d51aba4 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -60,7 +60,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 = 2365; +pub const SEMANTICS_VERSION: u32 = 2366; /// 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/error/mod.rs b/crates/metal2vulkan/src/error/mod.rs index e71bb29f9..51368f00d 100644 --- a/crates/metal2vulkan/src/error/mod.rs +++ b/crates/metal2vulkan/src/error/mod.rs @@ -606,8 +606,7 @@ pub enum Feature { }, /// A kernel's partial-threadgroups variant (`LoweringInputs::partial_threadgroups`) that the /// lowering cannot make, its cause named (`PartialThreadgroupsCause`): a tile function, one - /// with compute derivatives or an imageblock slice write every invocation shares, a body whose - /// uniform barriers need a vote word that the stage's workgroup memory cannot hold beside its + /// with compute derivatives, a body whose uniform barriers need a vote word that the stage's workgroup memory cannot hold beside its /// static arena, or the input beside `flat_grid`, `folded_groups` or `replay_bindings`. The /// kernel's dispatches keep the plain module's exact split. PartialThreadgroups, @@ -1365,10 +1364,6 @@ pub enum PartialThreadgroupsCause { /// each runs a dispatch other than the direct `dispatchThreads` whose invocations past the /// grid the variant walks. OtherForm, - /// An imageblock slice write every invocation of the threadgroup shares, each writing a - /// strided share of the slice's cells after a threadgroup barrier: invocations past the grid - /// would write no share. - SharedSliceWrite, /// A tile function (`LoweringInputs::tile_attachments`): its threadgroups are its tile's. TileFunction, /// Workgroup-uniform barriers that the walk takes to with a vote word, which the stage's diff --git a/crates/metal2vulkan/src/lower/mesh/mod.rs b/crates/metal2vulkan/src/lower/mesh/mod.rs index 0e38f9dfd..fe6a55dad 100644 --- a/crates/metal2vulkan/src/lower/mesh/mod.rs +++ b/crates/metal2vulkan/src/lower/mesh/mod.rs @@ -428,10 +428,11 @@ pub fn check_payload(cx: &SelectCx<'_>, size: u64) -> Result<(), Error> { /// (`simd::divergent::barriers`, `Predication::partial_groups`), so they walk to each barrier /// without running anything else of it. A kernel's `[[stage_in]]` attributes are fetched at entry /// after the returns, and a walked invocation's fetch reads a grid thread's element -/// (`lower::stage_io::stage_in`). A tile function, one with compute derivatives (whose quads a -/// returned lane would leave partial) and one with a cooperative imageblock slice write -/// (`texture::cooperative`, whose cells every invocation of the workgroup shares) are refused the -/// kernel's input, `Unsupported{PartialThreadgroups, NotImplemented}` naming the structure +/// (`lower::stage_io::stage_in`). A cooperative imageblock slice write (`texture::cooperative`) is +/// one of the walk's synchronizations: Metal's threads write the slice's cells among them, and +/// every invocation reaches its barrier. A tile function and one with compute derivatives (whose +/// quads a returned lane would leave partial) are refused the kernel's input, +/// `Unsupported{PartialThreadgroups, NotImplemented}` naming the structure /// (`PartialThreadgroupsCause`). Called before the push fields are placed. pub fn plan_partial_groups(cx: &mut SelectCx<'_>) -> Result<(), Error> { match cx.stage { @@ -441,8 +442,6 @@ pub fn plan_partial_groups(cx: &mut SelectCx<'_>) -> Result<(), Error> { Some(PartialThreadgroupsCause::TileFunction) } else if cx.families.barrier.compute_derivatives { Some(PartialThreadgroupsCause::ComputeDerivatives) - } else if !cx.families.texture.cooperative.is_empty() { - Some(PartialThreadgroupsCause::SharedSliceWrite) } else { None }; diff --git a/crates/metal2vulkan/src/lower/simd/divergent.rs b/crates/metal2vulkan/src/lower/simd/divergent.rs index fa8f00b6c..8fc00f1da 100644 --- a/crates/metal2vulkan/src/lower/simd/divergent.rs +++ b/crates/metal2vulkan/src/lower/simd/divergent.rs @@ -15,7 +15,10 @@ //! multiply-add, and control barrier (a simdgroup barrier is a workgroup barrier in the //! emulated tier; a threadgroup barrier after an early return must be reached by the returned //! invocations too, or the barriers of the live ones would pair with the returned ones' next -//! exchange). A block that holds one is a sync block. +//! exchange), and an imageblock slice write every invocation shares, which ends in a workgroup +//! barrier (`texture::shared_slice`: the invocations live there write its cells among them). A +//! block that holds one is a sync block. The shared slice is never itself the reason a function +//! is walked: its guard's branch, at a workgroup-uniform point, is taken by every invocation. //! - **Uniform facts** for the walk: the blocks `uniform::Uniformity` proves workgroup uniform //! (every invocation is live there, so the walk emits them as they are), and the branch //! conditions and switch selectors it proves uniform (a construct that branches on one in a @@ -51,7 +54,8 @@ //! atomic of theirs is made. A kernel of the emulated tier is walked so where it holds any of the //! tier's synchronizations (`workgroup::check`), and its exchanges take the lanes past its //! threadgroup's threads as outside it (`workgroup::Emu`). Outside the emulated tier only the -//! workgroup barriers are synchronizations ([`SyncSet::WorkgroupBarriers`]): a subgroup operation +//! workgroup barriers and the shared slices are synchronizations ([`SyncSet::WorkgroupBarriers`]): +//! a subgroup operation //! runs where `live` holds, so it sees the live invocations that execute it, its tangle in the //! source under maximal reconvergence. A loop vote there uses a workgroup word of its own //! (`RuntimeFact::PredicationVote`), declared when a synchronization lies in a loop. @@ -66,6 +70,7 @@ use crate::graph::LoopForest; use crate::lower::select::SelectCx; use crate::lower::strategy::{FamilyStrategy, Strategy}; use crate::lower::sync::barrier::{self, BarrierStrategy}; +use crate::lower::texture; use crate::pipeline::facts::RuntimeFact; use crate::pipeline::sym::Stage; use crate::spirv::ids::DemoteTy; @@ -84,7 +89,8 @@ pub enum SyncSet { #[default] Emulated, /// Every other tier: the control barriers emitted at `Workgroup` scope - /// (`barrier::is_workgroup_barrier`, which knows the function's `stage` and `tier`). A + /// (`barrier::is_workgroup_barrier`, which knows the function's `stage` and `tier`), and the + /// imageblock slice writes every invocation shares (`texture::shared_slice`). A /// subgroup or quad operation, a multiply-add, and a subgroup-scope barrier run where `live` /// holds, like any other instruction. WorkgroupBarriers { stage: Stage, tier: Tier }, @@ -96,7 +102,7 @@ impl SyncSet { match self { SyncSet::Emulated => is_sync(s), SyncSet::WorkgroupBarriers { stage, tier } => { - barrier::is_workgroup_barrier(s, stage, tier) + barrier::is_workgroup_barrier(s, stage, tier) || texture::shared_slice(s) } } } @@ -156,7 +162,7 @@ pub fn is_sync(s: &Strategy) -> bool { | SimdStrategy::Matrix(MatrixStrategy::Mac(_)) | SimdStrategy::Agx(AgxStrategy::MatMad(_)) ) - ) + ) || texture::shared_slice(s) } /// Plan the predicated walk of the kernel of `cx` with synchronizations `set`: the uniform and sync @@ -301,7 +307,7 @@ pub fn barriers( .inst(id) .and_then(|v| strategy.get(v.index())) .and_then(Option::as_ref) - .is_some_and(|s| set.holds(s)) + .is_some_and(|s| set.holds(s) && !texture::shared_slice(s)) }) }); if !divergent && !partial { diff --git a/crates/metal2vulkan/src/lower/simd/workgroup.rs b/crates/metal2vulkan/src/lower/simd/workgroup.rs index 84b481d0c..7e9c7a1ce 100644 --- a/crates/metal2vulkan/src/lower/simd/workgroup.rs +++ b/crates/metal2vulkan/src/lower/simd/workgroup.rs @@ -344,7 +344,7 @@ fn divergent_site( .inst(id) .and_then(|v| strategy.get(v.index())) .and_then(Option::as_ref) - .is_some_and(divergent::is_sync); + .is_some_and(|s| divergent::is_sync(s) && !crate::lower::texture::shared_slice(s)); if site { return Some((b.raw(), id.raw())); } diff --git a/crates/metal2vulkan/src/lower/texture/cooperative.rs b/crates/metal2vulkan/src/lower/texture/cooperative.rs index a43814a76..6d7416b3d 100644 --- a/crates/metal2vulkan/src/lower/texture/cooperative.rs +++ b/crates/metal2vulkan/src/lower/texture/cooperative.rs @@ -41,6 +41,15 @@ //! values without effect. The barrier after the shared loop orders every share before any //! invocation goes on to store a cell again. A slice write any condition fails keeps the serial //! loop. +//! +//! In a predicated walk (`simd::divergent`) the shared write is one of the walk's +//! synchronizations (`super::shared_slice`): every invocation reaches its barrier, and the +//! invocations live there take the shares. In a kernel's partial threadgroup +//! (`LoweringInputs::partial_threadgroups`) those are Metal's threads, which then write every cell +//! of the slice among them; a cell none of them stored holds zero, as the threadgroup's memory +//! starts. That is what the M3 Max recorded for Metal's own partial threadgroup, whose one write +//! lands zero for the cells of the threads past the grid (probe `imageblock_slice_past_the_grid`): +//! the zero is measured, not documented. use crate::air::abi::{Builtin, ImageblockKind, ParamRole, Stage}; use crate::air::intrinsics::{ diff --git a/crates/metal2vulkan/src/lower/texture/emit.rs b/crates/metal2vulkan/src/lower/texture/emit.rs index 63f675376..f0199f095 100644 --- a/crates/metal2vulkan/src/lower/texture/emit.rs +++ b/crates/metal2vulkan/src/lower/texture/emit.rs @@ -2403,9 +2403,43 @@ fn slice_texel(fb: &mut FunctionBuilder<'_>, form: TexelForm, v: SValue) -> BRes /// `(k mod bw, k / bw)` of a `bw ยท bh` block clipped to the imageblock, whose element at the /// field's offset is written at `coord + (x, y)`, discarded outside the texture. A cooperative /// slice (`super::cooperative`) runs in every invocation: cells `k = lin, lin + n, ...`, `lin` -/// the invocation's index in the threadgroup and `n` its threads, then a workgroup barrier over -/// the arena, so that no invocation stores a cell before every share is written. +/// the invocation's index in the threadgroup and `n` the invocations that share it, then a +/// workgroup barrier over the arena, so that no invocation stores a cell before every share is +/// written. In a predicated walk it is a synchronization (`super::shared_slice`): only the +/// invocations live there take a share, Metal's threads (`n` the threads a partial threadgroup +/// runs, `EmitCx::entry_threads`, whose `lin` are the first), and every invocation reaches the +/// barrier. A cell none of Metal's threads stored is written as the workgroup's memory holds it, +/// zero from its start (`access::local`'s zeroed arena). fn slice<'c>(cx: &mut EmitCx<'c>, fb: &mut FunctionBuilder<'_>, s: &Slice) -> BResult<()> { + match cx.live.filter(|_| s.cooperative) { + Some(live) => { + let s = *s; + let cells: ArmFn<'_, EmitCx<'c>> = Box::new(move |fb, cx| { + slice_cells(cx, fb, &s)?; + Ok(ArmEnd::FallThrough(Vec::new())) + }); + fb.if_(cx, live, cells, None)?; + } + None => slice_cells(cx, fb, s)?, + } + if s.cooperative { + let flags = crate::air::intrinsics::MemFlags { + threadgroup_imageblock: true, + ..Default::default() + }; + let sem = crate::lower::sync::barrier::semantics( + flags, + MemoryOrder::AcquireRelease, + memory_model(cx.plan), + ); + fb.control_barrier(Scope::Workgroup, Scope::Workgroup, sem)?; + } + Ok(()) +} + +/// The cells of slice `s` this invocation writes ([`slice`]): all of them, or a cooperative +/// slice's share. +fn slice_cells<'c>(cx: &mut EmitCx<'c>, fb: &mut FunctionBuilder<'_>, s: &Slice) -> BResult<()> { let Loaded { decl, img, @@ -2497,23 +2531,12 @@ fn slice<'c>(cx: &mut EmitCx<'c>, fb: &mut FunctionBuilder<'_>, s: &Slice) -> BR Ok(()) }); fb.loop_(cx, LoopSpec::default(), body)?; - if s.cooperative { - let flags = crate::air::intrinsics::MemFlags { - threadgroup_imageblock: true, - ..Default::default() - }; - let sem = crate::lower::sync::barrier::semantics( - flags, - MemoryOrder::AcquireRelease, - memory_model(cx.plan), - ); - fb.control_barrier(Scope::Workgroup, Scope::Workgroup, sem)?; - } Ok(()) } /// A cooperative slice's first cell and step: the invocation's index in the threadgroup and the -/// threadgroup's threads. +/// invocations that share the slice, the threads a partial threadgroup runs in a walk of partial +/// threadgroups (`EmitCx::entry_threads`), else the workgroup's. fn shares(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult<(SValue, SValue)> { use crate::lower::dispatch::KernelBuiltin; let decl: &crate::lower::emit::Declared = cx.decl; @@ -2523,6 +2546,9 @@ fn shares(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult<(SValue, let lin = k.value(fb, KernelBuiltin::ThreadIndexInThreadgroup, &mut |fb| { cx.push_field(fb, crate::pipeline::sym::PushField::DispatchRegion) })?; + if let Some(n) = cx.entry_threads { + return Ok((lin, n)); + } let threads = k.running_threads(fb)?; let tx = fb.composite_extract(threads, &[0])?; let ty_ = fb.composite_extract(threads, &[1])?; diff --git a/crates/metal2vulkan/src/lower/texture/mod.rs b/crates/metal2vulkan/src/lower/texture/mod.rs index e212971c1..34bcda6a1 100644 --- a/crates/metal2vulkan/src/lower/texture/mod.rs +++ b/crates/metal2vulkan/src/lower/texture/mod.rs @@ -529,6 +529,19 @@ pub struct QueryOp { pub volume: bool, } +/// Whether strategy `s` is an imageblock slice write every invocation of the workgroup shares +/// (`cooperative`), which ends in a workgroup barrier. A predicated walk takes it as one of its +/// synchronizations, so every invocation reaches the barrier and the invocations live there write +/// the slice's cells among them (`emit`'s slice), but never as a reason to walk: its guard's branch, +/// at a workgroup-uniform point, is taken by every invocation. +pub fn shared_slice(s: &crate::lower::strategy::Strategy) -> bool { + matches!( + s, + crate::lower::strategy::Strategy::Texture(TextureStrategy::ImageblockSlice(slice)) + if slice.cooperative + ) +} + /// The texture strategies. #[non_exhaustive] #[derive(Clone, Debug, PartialEq, Eq)] diff --git a/crates/metal2vulkan/src/pipeline/lower_inputs.rs b/crates/metal2vulkan/src/pipeline/lower_inputs.rs index d39cc3646..3de73b9b0 100644 --- a/crates/metal2vulkan/src/pipeline/lower_inputs.rs +++ b/crates/metal2vulkan/src/pipeline/lower_inputs.rs @@ -379,9 +379,13 @@ pub struct LoweringInputs { /// ballots its live lanes (`simd::partly_live`). On emulated simdgroups (the input /// `emulated_simdgroups`, or the profile's tier) the /// invocations past Metal's threads walk to each exchange too, and the exchanges take Metal's - /// threads as the threadgroup's (`simd::workgroup`). It declares `MultiRegion` and reads the + /// threads as the threadgroup's (`simd::workgroup`). An imageblock slice write every + /// invocation shares (`texture::cooperative`) is written by Metal's threads, among them, every + /// cell of the slice: a cell no thread of Metal's stored holds zero, as the threadgroup's + /// memory starts, which is what the M3 Max recorded for Metal's partial threadgroup (probe + /// `imageblock_slice_past_the_grid`). It declares `MultiRegion` and reads the /// region whatever builtins it reads, and states `RuntimeFact::PartialThreadgroups`. A tile - /// function, compute derivatives, an imageblock slice write every invocation shares, + /// function, compute derivatives, /// `flat_grid`, `folded_groups` and `replay_bindings` are `Unsupported{PartialThreadgroups, /// NotImplemented}`, and a body whose uniform barriers' vote word its workgroup memory cannot /// hold is `Unsupported{PartialThreadgroups}` needing the `Limit` of diff --git a/crates/metal2vulkan/src/tests/engine_partial_threadgroups.rs b/crates/metal2vulkan/src/tests/engine_partial_threadgroups.rs index 119fd580f..4b435001e 100644 --- a/crates/metal2vulkan/src/tests/engine_partial_threadgroups.rs +++ b/crates/metal2vulkan/src/tests/engine_partial_threadgroups.rs @@ -1,6 +1,7 @@ //! A kernel's partial-threadgroups variant (`LoweringInputs::partial_threadgroups`): it is //! refused with another form of the kernel's (a flat grid, folded groups, or a replay's bindings), -//! and made with emulated simdgroups. No GPU is used. +//! and made with emulated simdgroups and over an imageblock slice write every invocation shares. +//! No GPU is used. //! //! `llvm-as` assembles the kernels; a missing tool skips visibly. @@ -129,20 +130,15 @@ fn cause(u: &Unsupported) -> Option { } /// Each kernel structure the variant does not take is refused naming it, on every committed -/// profile that lowers the plain kernel: an imageblock slice write every invocation shares -/// (`engine_imageblock`'s `shared_slice` under its origin guard, `SharedSliceWrite`), compute -/// derivatives (`engine_dispatch`'s `store_const` with a `dfdx`, `ComputeDerivatives`) and a tile -/// function (`store_const` compiled under a tile attachment, `TileFunction`). +/// profile that lowers the plain kernel: compute derivatives (`engine_dispatch`'s `store_const` +/// with a `dfdx`, `ComputeDerivatives`) and a tile function (`store_const` compiled under a tile +/// attachment, `TileFunction`). #[test] fn each_structure_the_variant_does_not_take_names_its_cause() { use super::engine_dispatch::{store_const_with, DFDX, DFDX_DECL}; - use super::engine_imageblock::{shared_slice_kernel, ORIGIN_GUARD}; use crate::metal::PixelFormat; use crate::spirv::testing::committed_profiles; use std::collections::BTreeMap; - let Some(slice) = assemble_text("shared_slice", &shared_slice_kernel("", ORIGIN_GUARD)) else { - return; - }; let Some(derivatives) = store_const_with("ptg-dfdx", &[DFDX], &[DFDX_DECL]) else { return; }; @@ -152,12 +148,6 @@ fn each_structure_the_variant_does_not_take_names_its_cause() { let mut tile_inputs = LoweringInputs::new(); tile_inputs.tile_attachments = Some(BTreeMap::from([(0, PixelFormat::RGBA8Unorm)])); let kernels = [ - ( - slice, - "shared_slice", - LoweringInputs::new(), - "SharedSliceWrite", - ), ( derivatives, "store_const", diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 72371ef73..068c5efe0 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -8584,7 +8584,6 @@ variant metal2vulkan-runtime::OverCause::Surface Surface variant metal2vulkan-runtime::OverCause::ViewStorage ViewStorage variant metal2vulkan-runtime::PartialThreadgroupsCause::ComputeDerivatives ComputeDerivatives variant metal2vulkan-runtime::PartialThreadgroupsCause::OtherForm OtherForm -variant metal2vulkan-runtime::PartialThreadgroupsCause::SharedSliceWrite SharedSliceWrite variant metal2vulkan-runtime::PartialThreadgroupsCause::TileFunction TileFunction variant metal2vulkan-runtime::PartialThreadgroupsCause::VoteWord VoteWord variant metal2vulkan-runtime::PartialThreadgroupsSite::SimdGroups SimdGroups { width: u32 } @@ -9780,7 +9779,6 @@ variant metal2vulkan::error::Needs::NotImplemented NotImplemented variant metal2vulkan::error::Needs::NotRepresentable NotRepresentable variant metal2vulkan::error::PartialThreadgroupsCause::ComputeDerivatives ComputeDerivatives variant metal2vulkan::error::PartialThreadgroupsCause::OtherForm OtherForm -variant metal2vulkan::error::PartialThreadgroupsCause::SharedSliceWrite SharedSliceWrite variant metal2vulkan::error::PartialThreadgroupsCause::TileFunction TileFunction variant metal2vulkan::error::PartialThreadgroupsCause::VoteWord VoteWord variant metal2vulkan::error::PrivateRenderField::AlphaTest AlphaTest