diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index 127995b4c..381bbf9c8 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -1369,7 +1369,7 @@ codec_struct! { TextureReferenceType { data_type, texture_type, access, depth } KernelFacts { max_total_threads, work_group_size, flat_local_size, static_threadgroup_bytes, - partition_oblivious, partition_simdgroups, image_only, + partition_oblivious, partition_simdgroups, image_only, lockstep_in_rows, } StrategyCensus { entries } StrategyUse { uses, words } diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 3a06fefd8..702baac48 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -62,7 +62,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 = 2181; +pub const SEMANTICS_VERSION: u32 = 2182; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another @@ -72,7 +72,7 @@ pub const SEMANTICS_VERSION: u32 = 2181; /// re-typed in an encoded type, its `codec` body or its `envelope`. A variant removed while its tag /// stays unused needs no bump: an entry holding it fails to decode, which is a miss. The commit that /// bumps it says what changed; this comment keeps no history. -pub const ARTIFACT_FORMAT_VERSION: u32 = 536; +pub const ARTIFACT_FORMAT_VERSION: u32 = 537; /// The version of what this crate's runtime does with a compiled pipeline: instantiating a binding /// plan (`BindingPlan::instantiate_*`: descriptor ranges, push bytes, root, argument, and handle diff --git a/crates/metal2vulkan/src/library/compiled.rs b/crates/metal2vulkan/src/library/compiled.rs index fde1e7d81..65db1aa7b 100644 --- a/crates/metal2vulkan/src/library/compiled.rs +++ b/crates/metal2vulkan/src/library/compiled.rs @@ -320,6 +320,17 @@ impl CompiledFunction { self.0.kernel.partition_simdgroups } + /// Whether the function, a kernel, runs a barrier its lockstep order inserted (the barriers + /// for accesses only a simdgroup's lockstep orders) in a threadgroup whose simdgroups each lie + /// within one row: any of them but those that order only pairs meeting where a simdgroup + /// spans two rows, which run only where the threadgroup's size lets a simdgroup span two + /// (more than one row, of a width not a multiple of 32), a test the driver folds. Only where + /// this holds can its one-row variant (`LoweringInputs::one_row`) run fewer barriers there + /// than it does. `false` where the order inserted none. + pub fn runs_lockstep_barriers_in_rows(&self) -> bool { + self.0.kernel.lockstep_in_rows + } + /// Whether the function, a kernel, is image-only: it samples, gathers or reads a texture, and /// loads, stores and updates atomically nothing in device memory, through no load, store, /// atomic or call but a texture or sampler operation on a pointer into the `device` address @@ -500,4 +511,9 @@ pub struct KernelFacts { /// pointer into the `device` address space. Loads of `constant` memory and texture writes are /// allowed. Decided from the entry's AIR alone; `false` for a function that is not a kernel. pub image_only: bool, + /// The kernel's lockstep order inserted a barrier that runs where each simdgroup lies within + /// one row of its threadgroup: any of its barriers but those that order only pairs meeting + /// where a simdgroup spans two rows (`air::Lockstep::across_rows`), which run only where the + /// local size lets one span them. `false` where the order inserted none. + pub lockstep_in_rows: bool, } diff --git a/crates/metal2vulkan/src/lower/simd/lockstep.rs b/crates/metal2vulkan/src/lower/simd/lockstep.rs index 5a21ac77b..3a125bd8c 100644 --- a/crates/metal2vulkan/src/lower/simd/lockstep.rs +++ b/crates/metal2vulkan/src/lower/simd/lockstep.rs @@ -670,10 +670,10 @@ impl OrderKey { /// Order the threadgroup-memory and device-memory accesses of kernel `e` that only Apple's /// simdgroup lockstep orders, by inserting barriers into its body (see the module -/// documentation), for the device and variant of `key`. Where the key's one-row variant and -/// each simdgroup lying within one row orders no pair a simdgroup barrier would -/// ([`Lockstep::rows`]), only the threadgroup barriers are inserted. An entry of another stage, -/// or a kernel without such a pair, is returned unchanged. +/// documentation), for the device and variant of `key`. Where the key's one-row variant +/// (`LoweringInputs::one_row`) and, with each simdgroup lying within one row, no pair wants more +/// than a threadgroup barrier, only the threadgroup barriers are inserted, on every device. An +/// entry of another stage, or a kernel without such a pair, is returned unchanged. pub fn order(mut e: Entry, key: OrderKey, m: &mut Meter) -> Result { if !matches!(e.ep.stage, AbiStage::Kernel { .. }) { return Ok(e); @@ -771,11 +771,12 @@ fn decide( // `rows`). A threadgroup barrier none of them wants orders only pairs that meet where a // simdgroup spans two rows, so it runs only in such a threadgroup (`Order::Rows`). And where // none of them wants more than a threadgroup barrier, a dispatch of such threadgroups needs - // none of the simdgroup barriers; only a kernel whose subgroup barriers keep a 32-lane tier - // asks that (`tangle`, without the device's own lockstep). + // none of the simdgroup barriers (`cleared`): the one-row variant leaves them out on every + // device, and the plan states it (`rows`) where the kernel's subgroup barriers keep a 32-lane + // tier (`tangle`, without the device's own lockstep), the old binder's one-row regions. drop(af); let mut in_rows: BTreeSet = BTreeSet::new(); - if (tangle && !device) || wants.iter().any(|w| w.order == Order::Threadgroup) { + if one_row || (tangle && !device) || wants.iter().any(|w| w.order == Order::Threadgroup) { let mut rows_af = AddrFacts::new(e, body, &layouts, &us, true, m)?; for (_, acc) in &spaces { pairs( @@ -789,7 +790,8 @@ fn decide( )?; } } - let rows = tangle && !device && in_rows.iter().all(|w| w.order == Order::Threadgroup); + let cleared = in_rows.iter().all(|w| w.order == Order::Threadgroup); + let rows = tangle && !device && cleared; let mut wants: BTreeSet = wants .into_iter() .map( @@ -804,7 +806,7 @@ fn decide( .collect(); // The one-row variant keeps the threadgroup barriers alone: in a threadgroup whose simdgroups // each lie within one row, no pair a simdgroup barrier or an `Order::Rows` one orders meets. - if one_row && rows { + if one_row && cleared { wants.retain(|w| w.order == Order::Threadgroup); if wants.is_empty() { return Ok(None); diff --git a/crates/metal2vulkan/src/pipeline/compile.rs b/crates/metal2vulkan/src/pipeline/compile.rs index 37a9f75e0..609e60c44 100644 --- a/crates/metal2vulkan/src/pipeline/compile.rs +++ b/crates/metal2vulkan/src/pipeline/compile.rs @@ -3073,6 +3073,7 @@ impl Analyzed { partition_oblivious: observed == Partition::Oblivious, partition_simdgroups: observed == Partition::Simdgroups, image_only: self.image_only, + lockstep_in_rows: spec.lockstep.barriers.len() > spec.lockstep.across_rows.len(), }; Ok((plan, kernel)) } diff --git a/crates/metal2vulkan/src/pipeline/compile/tests.rs b/crates/metal2vulkan/src/pipeline/compile/tests.rs index 96d3db89a..b4c6f432f 100644 --- a/crates/metal2vulkan/src/pipeline/compile/tests.rs +++ b/crates/metal2vulkan/src/pipeline/compile/tests.rs @@ -1274,7 +1274,7 @@ fn the_old_render_descriptor_key_keeps_its_value() { let key = device("moltenvk-m3").render_descriptor_key(&d); let hex: String = key.digest().iter().map(|b| format!("{b:02x}")).collect(); assert_eq!( - hex, "4de8f0fc893ed8c1816ae0fdcb16ff96e5f9f190675ccccece23cc43ef8e79e0", + hex, "b3d05d42dc46deda08b46dcec16aeb05ffe9bb5f574be6a5c6a8ef1ea04d8764", "the old runtime's key of the descriptor" ); } diff --git a/crates/metal2vulkan/src/pipeline/facts.rs b/crates/metal2vulkan/src/pipeline/facts.rs index ccf4a716a..3cb04fcea 100644 --- a/crates/metal2vulkan/src/pipeline/facts.rs +++ b/crates/metal2vulkan/src/pipeline/facts.rs @@ -354,9 +354,10 @@ pub enum RuntimeFact { /// (`VariantKey::one_row`), which has none of those barriers. RowLockstep, /// The kernel was compiled under `VariantKey::one_row` (`LoweringInputs::one_row`): it runs - /// threadgroups whose simdgroups each lie within one row, without the lockstep simdgroup - /// barriers its `RowLockstep` plan had (its threadgroup ones kept). Its plans state the - /// variant, and a dispatch with a region of more than one row asks for the variant without it. + /// threadgroups whose simdgroups each lie within one row, without the lockstep barriers that + /// order only pairs meeting where a simdgroup spans two rows (its threadgroup ones kept), + /// whatever its device. Its plans state the variant, and a dispatch with a region of more than + /// one row asks for the variant without it. OneRow, /// Unit axes (`lower::simd::uniform`, "Unit axes"; bit 0 `x`, bit 1 `y`, bit 2 `z`). Where /// `axes` is 0, the kernel's walk is predicated and `relief` holds, at bit `m − 1`, each mask diff --git a/crates/metal2vulkan/src/pipeline/lower_inputs.rs b/crates/metal2vulkan/src/pipeline/lower_inputs.rs index acb4e87d9..103eee8e9 100644 --- a/crates/metal2vulkan/src/pipeline/lower_inputs.rs +++ b/crates/metal2vulkan/src/pipeline/lower_inputs.rs @@ -41,8 +41,9 @@ pub struct LoweringInputs { pub emulated_simdgroups: bool, /// A kernel runs threadgroups whose simdgroups each lie within one row /// (`VariantKey::one_row`): the lockstep barriers it takes are its threadgroup ones alone - /// where, so dispatched, no pair a simdgroup barrier orders meets (`air::Lockstep::rows`), and - /// with no simdgroup barrier it takes no simd class and pins no subgroup for them. A kernel + /// where, so dispatched, no pair wants more than a threadgroup barrier, on every device (the + /// old binder asks for it where `air::Lockstep::rows` holds), and with no simdgroup barrier it + /// takes no simd class and pins no subgroup for them. A kernel /// compiled under it depends on `RuntimeFact::OneRow`. Any other function compiles as without /// it. #[cfg_attr(feature = "serde", serde(default))] diff --git a/crates/metal2vulkan/src/tests/engine_simd_emulated.rs b/crates/metal2vulkan/src/tests/engine_simd_emulated.rs index 9634c5ede..e6651ff4b 100644 --- a/crates/metal2vulkan/src/tests/engine_simd_emulated.rs +++ b/crates/metal2vulkan/src/tests/engine_simd_emulated.rs @@ -2901,3 +2901,188 @@ fn a_texel_s_samples_in_a_row_need_no_emulated_simdgroups_on_wave64() { ); } } + +/// What a [`row_store_kernel`] stores. +#[derive(Clone, Copy, PartialEq, Eq)] +enum RowStores { + /// The three words `3 cell + k` of its cell `cell = y * stride + x`, in `int` arithmetic as + /// Apple compiles it (`nsw` on every step, the index sign-extended), which two threads of one + /// simdgroup in different rows may share for all the IR shows. + Cells, + /// The same words in `uint` arithmetic, whose steps carry no flags: a step may wrap, and the + /// order does not prove two threads of one row apart in such an index. + WrappingCells, + /// 1 at `x` and 2 at `x + 1`, which two threads of one row share. + Neighbours, +} + +/// A kernel over its position in the grid `(x, y)` that loads `src[x]` and stores to `dst`, of +/// buffers 0 and 1 and the uniform `stride` at buffer 2, what `stores` says; where `guarded`, only +/// a thread whose `x` is under `stride` does, past a branch on that test, as a kernel that bounds +/// its grid is compiled. +fn row_store_kernel(name: &str, stores: RowStores, guarded: bool) -> String { + let cells = |flags: &str, ext: &str| { + let mut body = format!( + "%row = mul{flags} i32 %w, %y + %cell = add{flags} i32 %row, %x + %d0 = mul{flags} i32 %cell, 3" + ); + for k in 0..3 { + if k > 0 { + body += &format!("\n %d{k} = add{flags} i32 %d0, {k}"); + } + body += &format!( + "\n %e{k} = {ext} i32 %d{k} to i64 + %p{k} = getelementptr inbounds i32, ptr addrspace(1) %dst, i64 %e{k} + store i32 %v, ptr addrspace(1) %p{k}, align 4" + ); + } + body + }; + let body = match stores { + RowStores::Cells => cells(" nsw", "sext"), + RowStores::WrappingCells => cells("", "zext"), + RowStores::Neighbours => "%e0 = zext i32 %x to i64 + %p0 = getelementptr inbounds i32, ptr addrspace(1) %dst, i64 %e0 + store i32 1, ptr addrspace(1) %p0, align 4 + %x1 = add i32 %x, 1 + %e1 = zext i32 %x1 to i64 + %p1 = getelementptr inbounds i32, ptr addrspace(1) %dst, i64 %e1 + store i32 2, ptr addrspace(1) %p1, align 4" + .to_owned(), + }; + let (test, body) = match guarded { + true => ( + "%inside = icmp ult i32 %x, %w + br i1 %inside, label %body, label %done + +body: + ", + format!("{body}\n br label %done\n\ndone:"), + ), + false => ("", body), + }; + 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 @{name}(ptr addrspace(1) %src, ptr addrspace(1) %dst, ptr addrspace(2) %stride, <2 x i32> %position) {{ + %y = extractelement <2 x i32> %position, i64 1 + %w = load i32, ptr addrspace(2) %stride, align 4 + %x = extractelement <2 x i32> %position, i64 0 + {test}%c = zext i32 %x to i64 + %ps = getelementptr inbounds i32, ptr addrspace(1) %src, i64 %c + %v = load i32, ptr addrspace(1) %ps, align 4 + {body} + ret void +}} + +!air.kernel = !{{!0}} +!air.version = !{{!20}} +!air.language_version = !{{!21}} + +!0 = !{{ptr @{name}, !1, !2}} +!1 = !{{}} +!2 = !{{!3, !4, !5, !6}} +!3 = !{{i32 0, !"air.buffer", !"air.location_index", i32 0, 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", !"uint", !"air.arg_name", !"src"}} +!4 = !{{i32 1, !"air.buffer", !"air.location_index", i32 1, 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", !"uint", !"air.arg_name", !"dst"}} +!5 = !{{i32 2, !"air.buffer", !"air.buffer_size", i32 4, !"air.location_index", i32 2, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"stride"}} +!6 = !{{i32 3, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint2", !"air.arg_name", !"position"}} +!20 = !{{i32 2, i32 8, i32 0}} +!21 = !{{!"Metal", i32 4, i32 0, i32 0}} +"# + ) +} + +/// On lavapipe's `Device::from_queries` profile under the identity domains (the new runtime's), +/// whose 8-lane subgroups hold no 32-lane tier, the lockstep order gives the stores of every +/// [`row_store_kernel`] barriers and states no `RowLockstep`, each kernel with its stores in its +/// entry block and past a bounds test. The one-row variant (`LoweringInputs::one_row`) clears +/// every pair of the cells kernel there too: no lockstep barrier, no simd class, `OneRow` stated; +/// with partial threadgroups it does not observe its threadgroup partition, which the variant +/// without `one_row` does, and its pipeline runs its grid in tiles (`GridTiles`, which the identity +/// domains state). The neighbours kernel's variant keeps its barriers, as its pair meets within +/// one row, and so does the wrapping cells kernel's, whose unflagged index the order does not +/// prove apart in rows. Every plain module runs a barrier where each simdgroup lies within one row +/// (`CompiledFunction::runs_lockstep_barriers_in_rows`) but the unguarded cells kernel's: its +/// barriers stand where the whole threadgroup runs and order only pairs that meet across rows, so +/// its module runs them only where a simdgroup spans two rows, and its one-row variant clears +/// nothing more at such a size. Past the bounds test they are simdgroup barriers, which run there. +#[test] +fn a_one_row_variant_clears_the_pairs_apart_in_rows_without_a_32_lane_tier() { + let desc = crate::pipeline::testing::description("lavapipe").unwrap_or_else(|e| panic!("{e}")); + let dev = Device::from_queries(desc, identity()).unwrap_or_else(|e| panic!("{e}")); + let p = dev.profile(); + let budget = Budget::standard(); + let mut one_row = LoweringInputs::new(); + one_row.one_row = true; + let lockstep = |plan: &Plan| { + (plan.census().keys()) + .filter(|name| name.starts_with("barrier.lockstep")) + .count() + }; + for (name, stores, guarded) in [ + ("row_cells", RowStores::Cells, false), + ("row_cells_wrapping", RowStores::WrappingCells, false), + ("row_neighbours", RowStores::Neighbours, false), + ("row_cells_guarded", RowStores::Cells, true), + ("row_cells_wrapping_guarded", RowStores::WrappingCells, true), + ("row_neighbours_guarded", RowStores::Neighbours, true), + ] { + let Some(bc) = assemble_text(name, &row_store_kernel(name, stores, guarded)) else { + return; + }; + let (plain, _) = typed_module(&bc, name, p).unwrap_or_else(|e| panic!("{name}: {e}")); + assert!(lockstep(&plain) > 0, "{name}: {:?}", plain.census()); + assert!(!plain.facts.contains(&RuntimeFact::RowLockstep), "{name}"); + let f = Library::from_air(&bc) + .ok() + .and_then(|lib| lib.function(name).ok()) + .map(FunctionDescriptor::new) + .expect("kernel"); + let own = dev + .compile_function(&f, &LoweringInputs::new(), &budget) + .unwrap_or_else(|e| panic!("{name}: {e}")); + assert_eq!( + own.runs_lockstep_barriers_in_rows(), + guarded || stores != RowStores::Cells, + "{name}: {:?}", + plain.census() + ); + let (row, _) = + typed_module_with(&bc, name, p, &one_row).unwrap_or_else(|e| panic!("{name}: {e}")); + assert!(row.facts.contains(&RuntimeFact::OneRow), "{name}"); + if stores != RowStores::Cells { + assert!(lockstep(&row) > 0, "{name}: {:?}", row.census()); + continue; + } + assert_eq!(lockstep(&row), 0, "{name}: {:?}", row.census()); + assert_eq!(row.simd, (SimdClass::None, Tier::NoSubgroup), "{name}"); + let entries = crate::pipeline::StageEntries::new(); + let mut partial = LoweringInputs::new(); + partial.partial_threadgroups = true; + let mut rows = partial.clone(); + rows.one_row = true; + let observes = |inputs: &LoweringInputs| { + dev.kernel_observes_partition(&f, inputs, &budget, &entries) + .unwrap_or_else(|e| panic!("{name}: {e}")) + }; + assert!(observes(&partial), "{name}: the partial variant"); + assert!(!observes(&rows), "{name}: the one-row partial variant"); + let compiled = dev + .compile_function(&f, &rows, &budget) + .unwrap_or_else(|e| panic!("{name}: {e}")); + assert!(!compiled.observes_threadgroup_partition(), "{name}"); + let pipeline = dev + .compile_compute_pipeline( + &ComputePipelineDescriptor::new(StageSource::Compiled(compiled)), + &budget, + ) + .unwrap_or_else(|e| panic!("{name}: {e}")); + assert!( + (pipeline.dependencies.iter()).any(|d| d.fact == RuntimeFact::GridTiles), + "{name}: {:?}", + pipeline.dependencies + ); + } +} diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index cbdee6e66..f35f19c37 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -11177,6 +11177,7 @@ method metal2vulkan::library::CompiledFunction::required_subgroup_size pub fn re method metal2vulkan::library::CompiledFunction::requirements pub fn requirements(&self) -> &Requirements method metal2vulkan::library::CompiledFunction::requires_full_subgroups pub fn requires_full_subgroups(&self) -> bool method metal2vulkan::library::CompiledFunction::resolves_handles pub fn resolves_handles(&self) -> bool +method metal2vulkan::library::CompiledFunction::runs_lockstep_barriers_in_rows pub fn runs_lockstep_barriers_in_rows(&self) -> bool method metal2vulkan::library::CompiledFunction::slots pub fn slots(&self) -> &BTreeMap method metal2vulkan::library::CompiledFunction::stage pub fn stage(&self) -> Stage method metal2vulkan::library::CompiledFunction::strategies pub fn strategies(&self) -> &StrategyCensus diff --git a/docs/API.md b/docs/API.md index 0275763f8..46bde30f3 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1924,6 +1924,12 @@ region states no grid and is unflagged, and all of its invocations run. lowering, what `CompiledFunction::observes_threadgroup_partition` answers for the compile under the same inputs (from the specialized entry `entries` holds, ordered for the device), so a runtime lowers only the variant a creation needs. +`CompiledFunction::runs_lockstep_barriers_in_rows` (`KernelFacts::lockstep_in_rows`) states +whether a kernel's lockstep order inserted a barrier that runs in a threadgroup whose simdgroups +each lie within one row: any but those that order only pairs meeting where a simdgroup spans two +rows, which the module runs only where its local size lets a simdgroup span them, a test of +specialization constants the driver folds. Only where it holds can the kernel's one-row variant +(`LoweringInputs::one_row`) run fewer barriers than its own module at such a size. `CompiledFunction::is_image_only` (`KernelFacts::image_only`) states, from the AIR alone, a kernel that samples, gathers or reads a texture and loads, stores and updates atomically nothing through a `device` pointer (`constant` loads and texture writes allowed), which a runtime may run in