Translator and runtime: a kernel's partial threadgroup writes its shared slice among Metal's threads

The partial-threadgroups variant refused a kernel with an imageblock slice write every
invocation shares (texture::cooperative), as SharedSliceWrite. The walk guarded the shared
write like any other instruction, so its trailing workgroup barrier stood under `if live`,
and the walked invocations past Metal's threads skipped their shares. It now takes the shared
slice as one of the walk's synchronizations, on every tier (texture::shared_slice, in
SyncSet::WorkgroupBarriers and divergent::is_sync):

- every invocation reaches the slice's barrier;
- the invocations live at the slice write the slice's cells among them. In a partial
  threadgroup those are Metal's threads: the first EmitCx::entry_threads invocations by lin.
  The step of the shared loop is now that count rather than the workgroup's size, so Metal's
  threads write every cell;
- a cell no thread of Metal's stored holds zero, the threadgroup arena's null initializer;
- the walked invocations store nothing in their cells before the barrier (the predicated walk).

The M3 Max recorded the same for Metal's own partial threadgroup, so this matches the
measurement rather than any documented rule. Probe imageblock_slice_past_the_grid, job
m3-max-85078: each cell of a thread past the grid lands zero, in two runs of two dispatches.
No MSL or Metal text says what such a cell holds, and the docs claim nothing beyond the
recording.

The shared slice is never by itself a reason to walk. Its guard's branch, at a
workgroup-uniform point, is taken by every invocation, so a kernel whose only non-uniform
synchronization is a shared slice keeps its unwalked module. Outside a walk the shared loop is
unchanged.

- error: PartialThreadgroupsCause::SharedSliceWrite goes, since nothing else raises it.
  mesh::plan_partial_groups no longer refuses the variant for it. Feature::PartialThreadgroups'
  and LoweringInputs::partial_threadgroups' docs drop it and say what the slice writes.
- runtime: its cache's refusal markers drop m2v-refused-slice (cache::REFUSALS has 5 entries).
  PartialThreadgroupsSite::Structure's doc and the README's gap paragraph drop the slice.
  Caches::refused now reads a variant's translation file in one lookup (the planner's
  read-back of the cause table). It asked the store once per marker, and each Store::holds
  opened the file in young and then old, and read it whole where its length was the marker's.
  Three markers are 16 bytes, so one 16-byte file was read up to three times. Store::holds_one
  takes the markers with their tags, opens the file once a generation, reads it only where its
  length is a marker's, and matches the bytes against each. Store::holds is holds_one of one
  marker. A hit in old still moves into young. Lookups count their opens under the tests
  (Store::file_opens).
- tests:
  - the red test turns green;
  - each_structure_the_variant_does_not_take_names_its_cause keeps compute derivatives and
    the tile function;
  - the runtime's marker test drops the cause;
  - api_signatures.tsv loses the two variant rows. REFUSALS.md and basis.rs regenerate
    unchanged.
  - a_variant_refusal_is_read_back_in_one_lookup_of_its_file writes each marker of REFUSALS
    under a key of its own and reads each back with exactly one open. A missing key opens at
    most twice, and a lowering of a marker's length is no refusal.
- SEMANTICS_VERSION 2366 (renumbered at landing: 2363-2365 went to arm 9, the blob move and the 1D bicubic): a partial-threadgroups
  variant with a shared slice now compiles. RUNTIME_VERSION stays: no run of an unchanged
  artifact differs, and the runtime-source fingerprint's inputs are untouched.

Verified:
- red d1d4b5cc9c, job m3-max-85298: a_partial_threadgroup_s_shared_slice_holds_zero_past_its_threads
  fails at its compile ("unsupported: PartialThreadgroups: SharedSliceWrite"), and the filter's
  other 20 tests pass. With Caches::refused asking once per marker, as before, the same job's
  a_variant_refusal_is_read_back_in_one_lookup_of_its_file fails at 2 opens for
  Structure(ComputeDerivatives). Green: 23 passed.
- suites (85298): product 3498 passed, 1 failed (golden_hashes_match_the_table, re-blessed on
  development), 24 skipped; validation 1344 passed, 2 skipped; conformance 1055 passed,
  0 skipped; doctests EXIT=0.
- clippy plain 85194, m2v_gpu 85193 and m2v_cpu_icd 85197 EXIT=0; rustdoc and api-docs 85195
  EXIT=0, all at the tree of this change and the case that follows it.
- the guest's kernels, job m3-max-85164 (release, a Ryzen 7 7840HS): the two kernels this
  refusal held in a recording's libraries lower and pass spirv-val on all 15 committed profiles,
  under the plain module and both partial-threadgroups variants. The slowest row is moltenvk-m3's
  emulated variant at 0.017 s, and the peak resident set is 32.6 MiB a process. Before this
  change both variants were refused as SharedSliceWrite (job m3-max-85052).
- Metal's own answer, in the conformance case that follows (compute-imageblock-slice-past-the-
  grid): recorded on the M3 (m3-max-85134), and equal on llvmpipe and on the RX 7900 XTX
  (m3-max-85149).
This commit is contained in:
Anees Iqbal committed 2026-12-03 13:12:41 -08:00
1 parent 7e1ca1af89
commit ddfc3a6da4
16 files changed
+176 -78

No files matched your search

+2 -2
View File
@@ -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
+49 -19
View File
@@ -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<T>,
) -> Option<T> {
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<Self>, 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<T: Copy>(
self: &Arc<Self>,
file: &str,
markers: &[(T, &[u8])],
) -> Option<T> {
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<T>(
self: &Arc<Self>,
file: &str,
len: Option<u64>,
fits: impl Fn(u64) -> bool,
decode: impl FnOnce(&[u8]) -> Option<T>,
torn: bool,
) -> Option<T> {
@@ -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<u64>) -> io::Result<Option<Vec<u8>>> {
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<Option<Vec<u8>>> {
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<VariantRefusal> {
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<Store>> {
self.store.as_ref()
}
/// Whether the translator answered on a device before that the kernel whose
+1 -1
View File
@@ -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,
+30 -1
View File
@@ -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");
@@ -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];
+1 -1
View File
@@ -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
+1 -6
View File
@@ -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
+5 -6
View File
@@ -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
};
@@ -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 {
@@ -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()));
}
@@ -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::{
+41 -15
View File
@@ -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])?;
@@ -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)]
@@ -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
@@ -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<String> {
}
/// 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",
@@ -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
Can't render this file because it is too large.