Translator: a kernel variant's lowering inputs come from LoweringInputs::kernel_variant; rt answers its translator

rt's kernel state lowered its partial-threadgroups and emulated-SIMD-group variants under inputs it
assembled by hand: a clone of the plain module's inputs with one flag set. Validation's executor is
to lower the same variants on the same device to read each module's containment of an
out-of-bounds target, so the assembly moves into the translator as the one constructor both call:
KernelVariant (Plain, PartialThreadgroups, EmulatedSimdgroups; ALL) and
LoweringInputs::kernel_variant, applied to the inputs kernel_inputs_read gives. rt's
Compiled::of and its translate tests' helpers call it.

metal2vulkan-runtime's Device::translator returns the translator device creation built, the one
every state lowers on. It retains nothing new (it borrows Core::translator) and has no Metal
counterpart.

One rt device test pins the agreement: for icb_replay_grid_template (its plain module checks the
store at a computed index, SlotBounds of buffer 1, and leaves the two constant-offset loads of
buffer 0 unchecked) and gsm2_simd_products' simd_float_products, every lowering a first device
kept in its cache directory is found under the key of one variant's public inputs, byte-equal to
Device::translator's compile_function of that variant, and at least as many are found as the
states made modules.

Surface: api_surface names KernelVariant (N); api_signatures blessed (8 records added, none
changed or removed); docs/API.md and the runtime README's compute-state section say how a
consumer lowers a variant. No public item is removed, so no consumer search applies.

Verified: cargo fmt; the compile gate and the runtime's device tests on lavapipe follow as a
potluck job.
This commit is contained in:
Anees Iqbal committed 2026-11-20 21:27:19 -08:00
1 parent 0dc56519c9
commit 47f804e943
9 files changed
+201 -16

No files matched your search

+4
View File
@@ -2186,6 +2186,10 @@ while the driver's exit handler waited on a lock, with every runtime thread alre
reflection from the library's AIR. The options it leaves to the consumer are
`MTLPipelineOptionFailOnBinaryArchiveMiss`, `MTLPipelineOptionArgumentInfo`,
`MTLPipelineOptionBufferTypeInfo` and `MTLPipelineOptionBindingInfo`.
- `Device::translator` (no Metal counterpart) is the translator device creation built. A state of
a kernel function lowers each module, the plain one and its variants, on it under
`LoweringInputs::kernel_variant` of the inputs its `kernel_inputs_read` gives the descriptor's,
so a consumer that lowers a variant there gets the module the state runs.
- What a state compiles is its content, never the state: its descriptor's kernel with its
constant values, linked functions and dynamic libraries, the descriptor's fields that change
the compile (the translator's `Device::compute_pipeline_key`), and its
@@ -847,6 +847,15 @@ impl Device {
self.shared.core.memory_types
}
/// No Metal counterpart: the translator device creation built, which every pipeline state of
/// the device lowers its functions on: the physical device's queries with what creation
/// enables, under the identity domains. The modules of a state of a kernel function
/// (`StageSource::Function`) are this device's lowerings of the kernel's variants, each under
/// `LoweringInputs::kernel_variant` of the inputs `kernel_inputs_read` gives the descriptor's.
pub fn translator(&self) -> &metal2vulkan::device::Device {
&self.shared.core.translator
}
/// No Metal counterpart: the Vulkan handles, for the consumer's swapchain and presents. The
/// runtime keeps owning them; the consumer destroys none of them, and destroys whatever it
/// makes with them before the device is torn down.
+8 -8
View File
@@ -68,9 +68,9 @@ use metal2vulkan::library::{CompiledFunction, FunctionCompileKey};
use metal2vulkan::metal::{BindingAccess, BindingType};
use metal2vulkan::pipeline::{
arena_bytes, AccessSet, Axis, BindingSource, BufferKind, CombinedSampler, ComputePipeline,
ComputePipelineDescriptor, DescriptorSetLayout, FunctionDescriptor, LoweringInputs,
NumberedSampler, PrecisionNote, PushField, PushLoc, RuntimeFact, SamplerRef, SlotClass,
SlotInterface, SlotRef, SpecKey, Stage, StageEntries, StageSource, TextureAccess,
ComputePipelineDescriptor, DescriptorSetLayout, FunctionDescriptor, KernelVariant,
LoweringInputs, NumberedSampler, PrecisionNote, PushField, PushLoc, RuntimeFact, SamplerRef,
SlotClass, SlotInterface, SlotRef, SpecKey, Stage, StageEntries, StageSource, TextureAccess,
DEEP_THREADGROUP, GRID_TILE_THREADS,
};
use metal2vulkan::Budget;
@@ -867,11 +867,11 @@ impl Compiled {
)
})
.map_err(Error::Translation)?;
let mut emulated = plain.clone();
emulated.emulated_simdgroups = true;
let source = (function, emulated);
let mut inputs = plain.clone();
inputs.partial_threadgroups = true;
let source = (
function,
plain.kernel_variant(KernelVariant::EmulatedSimdgroups),
);
let inputs = plain.kernel_variant(KernelVariant::PartialThreadgroups);
let lower =
|inputs: &LoweringInputs| lower(&core, function, inputs, &budget, entries);
// The partial-threadgroups variant: what the cache directory holds, else lowered
@@ -34,7 +34,7 @@ mod on_device {
DeviceOptions, DispatchType, Error, FunctionDescriptor, Gap, Gauges, Library, Limit,
MemoryClass, PrecisionNote, Refusal, Region, StageSource, MAX_BUFFER_LENGTH,
};
use metal2vulkan::pipeline::{RuntimeFact, StageEntries};
use metal2vulkan::pipeline::{KernelVariant, RuntimeFact, StageEntries};
use metal2vulkan::Budget;
use metal2vulkan_devtools::{engine_dir, llvm_assemble, AssembleError};
use std::path::{Path, PathBuf};
@@ -91,8 +91,8 @@ mod on_device {
translator.compile_compute_pipeline(descriptor, &budget),
)];
if let StageSource::Function(function) = &descriptor.kernel {
let mut inputs = descriptor.lowering_inputs();
inputs.partial_threadgroups = true;
let inputs = (descriptor.lowering_inputs())
.kernel_variant(KernelVariant::PartialThreadgroups);
let variant = translator
.compile_function(function, &inputs, &budget)
.and_then(|compiled| {
@@ -133,14 +133,13 @@ mod on_device {
let StageSource::Function(function) = &descriptor.kernel else {
unreachable!("a fixture's kernel is a function");
};
let translator = &device.core().translator;
let translator = device.translator();
let budget = Budget::standard();
let entries = StageEntries::new();
let plain = translator
.kernel_inputs_read(function, &descriptor.lowering_inputs(), &budget, &entries)
.unwrap_or_else(|error| panic!("{name}: {error}"));
let mut emulated = plain.clone();
emulated.emulated_simdgroups = true;
let emulated = plain.kernel_variant(KernelVariant::EmulatedSimdgroups);
[plain, emulated].map(|inputs| {
let compiled = translator
.compile_function_from_entries(function, &inputs, &budget, &entries)
@@ -165,6 +164,19 @@ mod on_device {
.is_some_and(|lowered| matches!(lowered, Lowered::Made(..)))
}
/// How many modules `state`'s make made: its whole one, and each variant it lowered with it.
fn modules_made(state: &ComputePipelineState) -> usize {
use crate::pipeline::{Form, Lowered};
let partial = match &state.inner.compiled.form {
Form::Sized {
partial: Some(lowered),
} => matches!(**lowered, Lowered::Made(..)),
_ => false,
};
1 + usize::from(partial) + usize::from(emulated_made(state))
}
/// Zeroed Shared buffers in one block, each at a 256-byte boundary.
struct Buffers {
device: Device,
@@ -1729,6 +1741,106 @@ mod on_device {
}
}
/// Each module a kernel's state lowers is the translator's public lowering of its variant on
/// the device's translator (`Device::translator`), under `LoweringInputs::kernel_variant` of
/// the inputs `kernel_inputs_read` gives: for the observing kernel, whose plain module checks
/// its one store at a computed index against its buffer (`PushField::SlotBounds` of buffer 1)
/// and leaves its two loads at constant offsets unchecked (none of buffer 0), and for a kernel
/// of SIMD-group products. Each lowering a first device kept in its cache directory is found
/// under the key of one variant's inputs, its artifact the public compile's byte for byte, and
/// as many are found as the states made modules.
#[test]
fn every_device_s_kernel_modules_are_the_translator_s_lowerings_of_their_variants() {
use metal2vulkan::pipeline::{PushField, SlotClass, SlotRef};
let (Some(observing), Some(products)) = (
descriptor("icb_replay_grid_template"),
descriptor_of("gsm2_simd_products", "simd_float_products"),
) else {
return;
};
let instance = crate::tests::validation::instance(&[]);
let devices = devices_of_the_cfgs_kind(&instance);
assert!(!devices.is_empty(), "no device of this cfg's kind");
for (name, physical) in &devices {
let dir = std::env::temp_dir().join(format!("m2v-rt-variants-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let first = on_directory(name, physical, &dir);
let counters = first.counters();
let states = [
state(name, &first, &observing),
state(name, &first, &products),
];
let made: usize = states.iter().map(modules_made).sum();
drop(states);
drop(first);
// The teardown ends once the reaper wrote what it was given.
within("the teardown", || counters.gauges() == Gauges::default());
let second = on_directory(name, physical, &dir);
let translator = second.translator();
let budget = Budget::standard();
let entries = StageEntries::new();
let mut found = 0;
for descriptor in [&observing, &products] {
let StageSource::Function(function) = &descriptor.kernel else {
unreachable!("a fixture's kernel is a function");
};
let plain = translator
.kernel_inputs_read(function, &descriptor.lowering_inputs(), &budget, &entries)
.unwrap_or_else(|error| panic!("{name}: {error}"));
for variant in KernelVariant::ALL {
let inputs = plain.kernel_variant(variant);
let key = translator.function_compile_key(function, &inputs);
let Some(kept) = crate::pipeline::loaded(second.core(), key.digest()) else {
continue;
};
let public = translator
.compile_function(function, &inputs, &budget)
.unwrap_or_else(|error| panic!("{name}: {variant:?}: {error}"));
assert!(
kept.to_bytes() == public.to_bytes(),
"{name}: the state's {variant:?} module is the public lowering"
);
found += 1;
}
}
assert!(
found >= made,
"{name}: {found} lowerings found of the {made} modules the states made"
);
let StageSource::Function(function) = &observing.kernel else {
unreachable!("a fixture's kernel is a function");
};
let mut plain = observing.clone();
plain.kernel = StageSource::Compiled(
translator
.compile_function(function, &observing.lowering_inputs(), &budget)
.unwrap_or_else(|error| panic!("{name}: {error}")),
);
let pipeline = translator
.compile_compute_pipeline(&plain, &budget)
.unwrap_or_else(|error| panic!("{name}: {error}"));
let checked: Vec<u32> = (pipeline.interface.push.iter())
.filter_map(|placement| match placement.field {
PushField::SlotBounds(SlotRef {
class: SlotClass::Buffer,
index,
..
}) => Some(index),
_ => None,
})
.collect();
assert_eq!(
checked,
[1],
"{name}: the buffers whose accesses are checked"
);
drop(second);
let _ = std::fs::remove_dir_all(&dir);
println!("{name}: {found} modules, each a variant's public lowering");
}
}
/// The second process's part of
/// `every_device_shares_the_cache_directory_with_a_second_process`: on the device and
/// directory it names, the first process's kernel, then a kernel of its own.
@@ -1214,6 +1214,54 @@ impl LoweringInputs {
pub fn new() -> LoweringInputs {
LoweringInputs::default()
}
/// The inputs of a kernel's `variant`, where these are its plain module's: a compute
/// pipeline's [`lowering_inputs`](crate::pipeline::ComputePipelineDescriptor::lowering_inputs)
/// narrowed to the attributes its kernel reads
/// ([`Device::kernel_inputs_read`](crate::device::Device::kernel_inputs_read)). These inputs
/// as they are for [`KernelVariant::Plain`]; with
/// [`partial_threadgroups`](Self::partial_threadgroups) for
/// [`KernelVariant::PartialThreadgroups`], and with
/// [`emulated_simdgroups`](Self::emulated_simdgroups) for
/// [`KernelVariant::EmulatedSimdgroups`]. A consumer that lowers a kernel's variants itself
/// builds each one's inputs here, so two consumers of one device lower one module per variant.
pub fn kernel_variant(&self, variant: KernelVariant) -> LoweringInputs {
let mut inputs = self.clone();
match variant {
KernelVariant::Plain => {}
KernelVariant::PartialThreadgroups => inputs.partial_threadgroups = true,
KernelVariant::EmulatedSimdgroups => inputs.emulated_simdgroups = true,
}
inputs
}
}
/// One of the modules a compute pipeline's kernel is lowered to
/// ([`LoweringInputs::kernel_variant`]): its plain module, and the variants a dispatch that the
/// plain module does not run as Metal runs it takes instead.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum KernelVariant {
/// The plain module: a whole number of threadgroups, each of whole SIMD groups where the
/// profile's subgroups give them.
Plain,
/// The partial-threadgroups variant ([`LoweringInputs::partial_threadgroups`]): a
/// `dispatchThreads` grid that is not a whole number of threadgroups, or a kernel that does
/// not observe its threadgroup partition in tiles of its grid.
PartialThreadgroups,
/// The emulated-SIMD-group variant ([`LoweringInputs::emulated_simdgroups`]): a threadgroup
/// that ends in a partial SIMD group.
EmulatedSimdgroups,
}
impl KernelVariant {
/// Every variant, the plain module first.
pub const ALL: [KernelVariant; 3] = [
KernelVariant::Plain,
KernelVariant::PartialThreadgroups,
KernelVariant::EmulatedSimdgroups,
];
}
/// How a storage image is declared and viewed for one bound pixel format.
+1 -1
View File
@@ -132,7 +132,7 @@ pub use layout::{
pub use link::{heap_sampler_capacity, heap_unused_while_pending};
pub use lower_inputs::{
AliasView, AmplificationDraws, BlendEquation, ChannelWrite, ExtendedRangeColor, FactorLane,
FetchedAttachment, FramebufferFetchInputs, LoweringInputs, RotatedBlendForm,
FetchedAttachment, FramebufferFetchInputs, KernelVariant, LoweringInputs, RotatedBlendForm,
StorageImageChoice, StorageImageClass, VertexFetch, VertexFetchProjection,
};
pub use table::FunctionHandle;
@@ -215,6 +215,7 @@ assoc-const metal2vulkan::pipeline::CommandWrites::THREADGROUP_MEMORY pub const
assoc-const metal2vulkan::pipeline::FanOutState::PUSH_BYTES pub const PUSH_BYTES: u32
assoc-const metal2vulkan::pipeline::FunctionHandle::NULL_WORD pub const NULL_WORD: u32
assoc-const metal2vulkan::pipeline::FunctionHandle::RESERVED_WORD pub const RESERVED_WORD: u32
assoc-const metal2vulkan::pipeline::KernelVariant::ALL pub const ALL: [KernelVariant; 3]
assoc-const metal2vulkan::pipeline::LineBandState::FRONT_FACE pub const FRONT_FACE: vk::FrontFace
assoc-const metal2vulkan::pipeline::LineBandState::PUSH_BYTES pub const PUSH_BYTES: u32
assoc-const metal2vulkan::vk::ComponentMapping::IDENTITY pub const IDENTITY: ComponentMapping
@@ -428,6 +429,7 @@ assoc-const-value metal2vulkan::pipeline::CommandWrites::THREADGROUP_MEMORY 1 <<
assoc-const-value metal2vulkan::pipeline::FanOutState::PUSH_BYTES crate::pipeline::link::fan_out::PUSH_BYTES
assoc-const-value metal2vulkan::pipeline::FunctionHandle::NULL_WORD 0
assoc-const-value metal2vulkan::pipeline::FunctionHandle::RESERVED_WORD 1
assoc-const-value metal2vulkan::pipeline::KernelVariant::ALL [KernelVariant::Plain, KernelVariant::PartialThreadgroups, KernelVariant::EmulatedSimdgroups]
assoc-const-value metal2vulkan::pipeline::LineBandState::FRONT_FACE crate::pipeline::link::band::LineBand::FRONT_FACE
assoc-const-value metal2vulkan::pipeline::LineBandState::PUSH_BYTES crate::pipeline::link::band::LineBand::PUSH_BYTES
assoc-const-value metal2vulkan::vk::ComponentMapping::IDENTITY ComponentMapping
@@ -932,6 +934,7 @@ enum metal2vulkan::pipeline::HandleClass #[cfg_attr(feature = "serde", derive(se
enum metal2vulkan::pipeline::ImageAccess #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum ImageAccess
enum metal2vulkan::pipeline::ImageDim #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum ImageDim
enum metal2vulkan::pipeline::ImageblockMechanism #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum ImageblockMechanism
enum metal2vulkan::pipeline::KernelVariant #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum KernelVariant
enum metal2vulkan::pipeline::LinkedList #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum LinkedList<'a>
enum metal2vulkan::pipeline::Mechanism #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum Mechanism
enum metal2vulkan::pipeline::NumberedSampler #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum NumberedSampler
@@ -6609,6 +6612,7 @@ method metal2vulkan-runtime::Device::report_loss pub fn report_loss(&self, loss:
method metal2vulkan-runtime::Device::supports_texture_sample_count pub fn supports_texture_sample_count(&self, count: u32) -> bool
method metal2vulkan-runtime::Device::take_block pub fn take_block(&self, class: MemoryClass, len: u64) -> Result<Block, Error>
method metal2vulkan-runtime::Device::texture_level_info pub fn texture_level_info(&self, query: &TextureLevelQuery) -> TextureLevelInfo
method metal2vulkan-runtime::Device::translator pub fn translator(&self) -> &metal2vulkan::device::Device
method metal2vulkan-runtime::Device::with_present_queue pub fn with_present_queue<R>(&self, f: impl FnOnce(vk::Queue) -> R) -> R
method metal2vulkan-runtime::Device::zero_block_range pub fn zero_block_range(&self, block: BlockId, offset: u64, length: u64) -> Result<(), Error>
method metal2vulkan-runtime::DeviceExtension::name pub fn name(&self) -> &CStr
@@ -7271,6 +7275,7 @@ method metal2vulkan::pipeline::LinkedList::resolves_references pub fn resolves_r
method metal2vulkan::pipeline::LinkedSource::new pub fn new(name: &'a str, bitcode: &'a [u8], constants: &'a FunctionConstantValues) -> LinkedSource<'a>
method metal2vulkan::pipeline::LinkedSource::with_specialized pub fn with_specialized(mut self, specialized: bool) -> LinkedSource<'a>
method metal2vulkan::pipeline::LinkedSource::with_specialized_name pub fn with_specialized_name(mut self, name: &'a str) -> LinkedSource<'a>
method metal2vulkan::pipeline::LoweringInputs::kernel_variant pub fn kernel_variant(&self, variant: KernelVariant) -> LoweringInputs
method metal2vulkan::pipeline::LoweringInputs::new pub fn new() -> LoweringInputs
method metal2vulkan::pipeline::MeshPipelineDescriptor::fragment_writes_depth_unattached pub fn fragment_writes_depth_unattached(&self, budget: &crate::Budget, entries: &StageEntries) -> Result<bool, Error>
method metal2vulkan::pipeline::MeshPipelineDescriptor::new pub fn new(mesh: StageSource) -> MeshPipelineDescriptor
@@ -10876,6 +10881,9 @@ variant metal2vulkan::pipeline::ImageDim::D1 D1
variant metal2vulkan::pipeline::ImageDim::D2 D2
variant metal2vulkan::pipeline::ImageDim::D3 D3
variant metal2vulkan::pipeline::ImageblockMechanism::StorageImageInterlock StorageImageInterlock
variant metal2vulkan::pipeline::KernelVariant::EmulatedSimdgroups EmulatedSimdgroups
variant metal2vulkan::pipeline::KernelVariant::PartialThreadgroups PartialThreadgroups
variant metal2vulkan::pipeline::KernelVariant::Plain Plain
variant metal2vulkan::pipeline::LinkedList::BinaryFunctions BinaryFunctions
variant metal2vulkan::pipeline::LinkedList::Functions Functions
variant metal2vulkan::pipeline::LinkedList::Group Group(&'a str)
Can't render this file because it is too large.
+1
View File
@@ -405,6 +405,7 @@ surface! {
enum FactorLane N;
struct FetchedAttachment N;
struct FramebufferFetchInputs N;
enum KernelVariant N;
struct LoweringInputs N;
enum RotatedBlendForm N;
struct StorageImageChoice N;
+4 -1
View File
@@ -1616,7 +1616,10 @@ assert_eq!(linked, pipeline);
compile a missing stage under. So does a compute pipeline's kernel:
`kernel_inputs_read(&kernel, &inputs, &budget, &entries)` narrows the stage-input descriptor to
the attributes its entry reads, and the kernel keys and compiles under those, so states that
differ only in an attribute it never reads share one compiled function. What a creation reads of
differ only in an attribute it never reads share one compiled function. Those are the plain
module's inputs; `inputs.kernel_variant(variant)` gives each `KernelVariant`'s (`Plain`,
`PartialThreadgroups`, `EmulatedSimdgroups`), so consumers that lower a kernel's variants on one
device lower one module per variant. What a creation reads of
the descriptor past the fetch -- its layout agreement, its reflection, and `compute_pipeline_key`
-- reads it whole.
- A key names an artifact by its inputs and versions; a content digest names it by what it says.