From 8734b6f6b7bd09036b80ca07989f1c28b5efc2e0 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Fri, 20 Nov 2026 21:57:45 -0800 Subject: [PATCH] probe: entry weights with the bound lifted, on the arena WIP, the switch form and resident tables (never landed) --- crates/metal2vulkan/src/bind/plan/compute.rs | 2 + crates/metal2vulkan/src/cache/codec.rs | 2 + crates/metal2vulkan/src/cache/mod.rs | 6 +- .../src/device/function_storage.rs | 11 +-- crates/metal2vulkan/src/device/mechanism.rs | 3 + crates/metal2vulkan/src/lower/access/local.rs | 40 ++++++++++- crates/metal2vulkan/src/lower/dispatch.rs | 72 ++++++++++++++++--- .../metal2vulkan/src/lower/dispatch/tests.rs | 1 + crates/metal2vulkan/src/lower/emit.rs | 30 ++++++++ crates/metal2vulkan/src/lower/push.rs | 3 +- .../metal2vulkan/src/lower/sampler/select.rs | 4 ++ crates/metal2vulkan/src/lower/select.rs | 9 ++- crates/metal2vulkan/src/memory/arena.rs | 71 +++++++++++++----- crates/metal2vulkan/src/memory/plan.rs | 59 +++++++++++---- .../src/pipeline/compile/stage_bound.rs | 8 ++- crates/metal2vulkan/src/pipeline/facts.rs | 9 +++ crates/metal2vulkan/src/pipeline/sym.rs | 9 +++ crates/metal2vulkan/src/spirv/interp/tests.rs | 10 ++- probe/allocas.py | 8 +-- probe/xlate.py | 65 +++++++++++------ 20 files changed, 344 insertions(+), 78 deletions(-) diff --git a/crates/metal2vulkan/src/bind/plan/compute.rs b/crates/metal2vulkan/src/bind/plan/compute.rs index 8ae3fbc67..1c0ecbc91 100644 --- a/crates/metal2vulkan/src/bind/plan/compute.rs +++ b/crates/metal2vulkan/src/bind/plan/compute.rs @@ -453,6 +453,8 @@ fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result { return Err(not_implemented(Feature::IdentityDomains)) } + // A private arena past the floor is the runtime's own memory, one slot an invocation. + PushField::PrivateArenaAddress => return Err(not_implemented(Feature::PrivateMemory)), PushField::SlotBindOffset(SlotRef { class: SlotClass::Texture, .. diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index 923c488a5..6ca23ee45 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -908,6 +908,7 @@ codec_enum! { ArgumentTableAddress, ConstexprSampler(f0), TessellationFactorAddress, + PrivateArenaAddress, SlotBounds(f0), ZeroAddress, FetchedColor { color, texels }, @@ -1309,6 +1310,7 @@ codec_enum! { TexelBufferParts { slot }, AddressAlignment { slot, align }, GridTiles, + PrivateArena { slot_bytes }, } UniformViewChoice { Viewed, Spare, Kept } Mechanism { diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index d69041920..3aa65c576 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -61,7 +61,7 @@ mod tests; /// unchanged version, and its bless records the version. Independent of the crate's version and of /// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no /// history. -pub const SEMANTICS_VERSION: u32 = 2235; +pub const SEMANTICS_VERSION: u32 = 2236; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another @@ -71,7 +71,7 @@ pub const SEMANTICS_VERSION: u32 = 2235; /// 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 = 574; +pub const ARTIFACT_FORMAT_VERSION: u32 = 575; /// 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 @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 574; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 2549; +pub const RUNTIME_VERSION: u32 = 2550; /// Writes a digest as lowercase hex. pub(crate) fn write_hex(f: &mut fmt::Formatter<'_>, name: &str, hash: &Hash256) -> fmt::Result { diff --git a/crates/metal2vulkan/src/device/function_storage.rs b/crates/metal2vulkan/src/device/function_storage.rs index 45538934a..3083487b5 100644 --- a/crates/metal2vulkan/src/device/function_storage.rs +++ b/crates/metal2vulkan/src/device/function_storage.rs @@ -13,10 +13,13 @@ //! runs up to [`METAL`], 192 KiB a thread, the most a Metal device was measured to hold, and //! records `PrecisionNote::FunctionStorageAssumed`: past the floor it rests on no measurement, and //! a driver that holds less can answer wrongly or hang the GPU, as the RTX 5080 at 48 KiB and the -//! RTX 3090 at 192 KiB hung when probed. A kernel, an object or a mesh function past the floor is -//! refused, as is a vertex or fragment function past [`METAL`]: typed (`Unsupported{PrivateMemory}`, -//! or `Unsupported{Recursion}` for a stage with a call stack, needing -//! `VkLimit::FunctionStorageBytesPerThread`). +//! RTX 3090 at 192 KiB hung when probed. A kernel without a call stack past the floor keeps the +//! private memory a run-time index reaches in device memory the runtime owns, one slot a thread +//! (`memory::plan::ArenaLayout::device`, `RuntimeFact::PrivateArena`), and what is left is held +//! to the floor. An object or a mesh function past the floor is refused, as are a kernel with a +//! call stack past it, a tile function past it, and a vertex or fragment function past [`METAL`]: +//! typed (`Unsupported{PrivateMemory}`, or `Unsupported{Recursion}` for a stage with a call stack, +//! needing `VkLimit::FunctionStorageBytesPerThread`). //! //! [`ProfileFields::function_storage`]: crate::device::profile::ProfileFields::function_storage diff --git a/crates/metal2vulkan/src/device/mechanism.rs b/crates/metal2vulkan/src/device/mechanism.rs index 157509adb..fe712b7e7 100644 --- a/crates/metal2vulkan/src/device/mechanism.rs +++ b/crates/metal2vulkan/src/device/mechanism.rs @@ -179,6 +179,9 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism { RuntimeFact::PartialThreadgroups => Mechanism::Variant, // The binder's regions carry the tile as the nominal size, under `MultiRegion` 1. RuntimeFact::GridTiles => Mechanism::RegionSelected, + // The runtime pushes its arena's address, and sizes and orders the arena's slots by the + // slot's bytes. + RuntimeFact::PrivateArena { .. } => Mechanism::PushConstant, // Keyed by the slots bound to a texture whose planes are read in place, on a profile that // reads them so (`ProfileFields::ycbcr_in_place`). RuntimeFact::YCbCrInPlace { .. } => Mechanism::Variant, diff --git a/crates/metal2vulkan/src/lower/access/local.rs b/crates/metal2vulkan/src/lower/access/local.rs index 8fa38adbd..f80be32d0 100644 --- a/crates/metal2vulkan/src/lower/access/local.rs +++ b/crates/metal2vulkan/src/lower/access/local.rs @@ -452,6 +452,9 @@ pub struct LocalPlan { pub tg: Option, /// The private arena's byte size, when a pointer into it is used. pub private: Option, + /// The private arena lives in device memory, an invocation's slot of the runtime's memory + /// (`memory::plan::ArenaLayout::device`). + pub private_device: bool, /// The payload's byte size (its parameter's `air.arg_type_size`), when a pointer into it is /// used. pub payload: Option, @@ -649,10 +652,31 @@ fn zero_threadgroup(cx: &mut SelectCx<'_>) -> Result<(), Error> { Ok(()) } +/// The private arena of `size` bytes in device memory (`ArenaLayout::device`): a slot of +/// `size` rounded up to 16 bytes for each invocation of a dispatch, at the address the runtime +/// pushes (`PushField::PrivateArenaAddress`), which the pipeline names with the slot's bytes +/// (`RuntimeFact::PrivateArena`). A tile function, whose invocations a render pass's tiles +/// place, keeps the refusal of private memory past the floor. +fn device_arena(cx: &mut SelectCx<'_>, size: u64) -> Result<(), Error> { + let slot = size.next_multiple_of(16); + if super::tile::is_tile(cx) { + let limit = Capability::Limit { + limit: crate::device::VkLimit::FunctionStorageBytesPerThread, + required: slot.saturating_add(cx.memory.private_bytes), + available: crate::device::function_storage::FLOOR, + }; + return Err(Unsupported::needs(Feature::PrivateMemory, limit).into()); + } + let slot_bytes = u32::try_from(slot).map_err(|_| Error::LimitExceeded(Limit::PrivateArenaBytes))?; + cx.push.insert(crate::pipeline::sym::PushField::PrivateArenaAddress); + cx.facts.insert(RuntimeFact::PrivateArena { slot_bytes }); + Ok(()) +} + /// Record that the function uses `arena`. The threadgroup arena's shape is fixed and checked /// against `maxComputeSharedMemorySize` once, and every region's length becomes a runtime fact of /// the function. A private arena past `budget::PRIVATE_ARENA_BYTES` is -/// `LimitExceeded(PrivateArenaBytes)`. +/// `LimitExceeded(PrivateArenaBytes)`; one in device memory is the runtime's ([`device_arena`]). pub(super) fn use_arena(cx: &mut SelectCx<'_>, arena: Arena) -> Result<(), Error> { match arena { Arena::Threadgroup => { @@ -726,6 +750,10 @@ pub(super) fn use_arena(cx: &mut SelectCx<'_>, arena: Arena) -> Result<(), Error if size > PRIVATE_ARENA_BYTES { return Err(Error::LimitExceeded(Limit::PrivateArenaBytes)); } + if cx.memory.priv_arena.device { + device_arena(cx, size)?; + cx.families.access.local.private_device = true; + } cx.families.access.local.private = Some(size); } } @@ -1113,7 +1141,7 @@ pub fn declare(mb: &mut ModuleBuilder, plan: &Plan) -> BResult { None => None, }, private: match p.private { - Some(size) => Some(arena::declare_private(mb, size)?), + Some(size) => Some(arena::declare_private(mb, size, p.private_device)?), None => None, }, payload: match p.payload { @@ -1944,6 +1972,9 @@ pub(super) fn decl_of( if let Some(tile) = fragment { decl.tile_base = Some(cx.tile_base(fb, tile)?); } + if arena == Arena::Private && cx.plan.families.access.local.private_device { + decl.slot = Some(cx.arena_slot(fb)?); + } Ok(decl) } @@ -2061,7 +2092,10 @@ fn float_words( } let two = k32(fb, 2)?; let first = fb.binary(BinOp::ShiftRightLogical, off, two)?; - let base = fb.module().global_value(decl.global)?; + let Some(global) = decl.global else { + return Err(cx.fail("an arena of float words without its array")); + }; + let base = fb.module().global_value(global)?; let access = ops.access(fb, MemAccess::default(), stored.is_some())?; let mut loaded = Vec::with_capacity(lanes as usize); for j in 0..lanes { diff --git a/crates/metal2vulkan/src/lower/dispatch.rs b/crates/metal2vulkan/src/lower/dispatch.rs index a3a593540..119167f8c 100644 --- a/crates/metal2vulkan/src/lower/dispatch.rs +++ b/crates/metal2vulkan/src/lower/dispatch.rs @@ -536,6 +536,9 @@ pub struct DispatchPlan { /// A kernel of the [`LocalSizeForm::Spec`] form without compute derivatives (whose quads are two-dimensional): it declares /// `SpecKey::DeepThreadgroup`, under which its threadgroup runs as one row (the module docs). pub deep: bool, + /// A kernel whose private arena lives in device memory (`memory::plan::ArenaLayout::device`): + /// each invocation reaches its slot by its index in its dispatch ([`arena_slot`]). + pub private_arena: bool, } /// The words a flat grid adds: its thread's index, position, and early return, derived once for the @@ -744,6 +747,7 @@ pub fn plan_kernel(cx: &mut SelectCx<'_>, tier: Tier) -> Result, fb: &mut FunctionBuilder<'_>) -> BResult< let Some(plan) = cx.plan.dispatch.as_ref() else { return Ok(()); }; + // The private arena's slot, in the first block, which every access of the arena reads. + if plan.private_arena { + cx.arena_slot(fb)?; + } // A flat grid's invocation past the grid's last thread returns before the body. Its position // is derived here once, with the test, and is the `thread_position_in_grid` every parameter // reads: a second derivation would repeat the divisions in a construct of its own, which the @@ -979,6 +987,8 @@ pub struct KernelDecl { uvec3: TypeId, /// `sx, sy, sz`. size: [ConstId; 3], + /// The `WorkgroupSize` composite. + workgroup: ConstId, /// `SpecKey::DeepThreadgroup`, where the plan declares it ([`DispatchPlan::deep`]). deep: Option, /// How the kernel tells a region, when it reads a grid builtin. @@ -1080,14 +1090,20 @@ impl Needs { .any(has) || (local_pos && (dp.local_size == LocalSizeForm::Flat || dp.tile)) || partial; + // A private arena in device memory counts its slot from the workgroup's position. + let arena = dp.private_arena; Needs { lin, local_pos, workgroup_id: folded || partial + || arena || has(K::ThreadPositionInGrid) || has(K::ThreadgroupPositionInGrid), - num_workgroups: folded || has(K::ThreadsPerGrid) || has(K::ThreadgroupsPerGrid), + num_workgroups: folded + || arena + || has(K::ThreadsPerGrid) + || has(K::ThreadgroupsPerGrid), } } } @@ -1240,7 +1256,7 @@ impl KernelDecl { .map(|(k, d)| mb.spec(k, u32_, ConstBits(u64::from(d)))); let size = [sx?, sy?, sz?]; let mut deep = None; - match dp.local_size { + let workgroup = match dp.local_size { LocalSizeForm::Spec if dp.deep => { let b = mb.ty(Type::Bool)?; let one_row = mb.spec(SpecKey::DeepThreadgroup, b, ConstBits(0))?; @@ -1252,12 +1268,10 @@ impl KernelDecl { })?; let [x, y, z] = [(sn, size[0]), (one, size[1]), (one, size[2])] .map(|(deep, own)| mb.spec_op(SpecOp::Select, u32_, &[one_row, deep, own])); - mb.workgroup_size(x?, y?, z?)?; deep = Some(one_row); + mb.workgroup_size(x?, y?, z?)? } - LocalSizeForm::Spec => { - mb.workgroup_size(size[0], size[1], size[2])?; - } + LocalSizeForm::Spec => mb.workgroup_size(size[0], size[1], size[2])?, LocalSizeForm::Flat => { let n = u64::from(dx) * u64::from(dy) * u64::from(dz); let sn = mb.spec(keys.flat, u32_, ConstBits(n))?; @@ -1265,9 +1279,9 @@ impl KernelDecl { ty: u32_, bits: ConstBits(1), })?; - mb.workgroup_size(sn, one, one)?; + mb.workgroup_size(sn, one, one)? } - } + }; let multi_region = match (dp.multi_region, dp.identity) { (false, _) => None, (true, identity) => { @@ -1291,7 +1305,8 @@ impl KernelDecl { // A grid tile counts by `LocalInvocationIndex` in either form too, and a deep // threadgroup's position is unflattened from it. let index = (needs.lin && (!flat || by_index || dp.grid_edge)) - || (needs.local_pos && deep.is_some()); + || (needs.local_pos && deep.is_some()) + || dp.private_arena; let subgroups = needs.lin && flat && !by_index && !dp.grid_edge; use crate::spv::BuiltIn as B; let mut var = |on: bool, b: crate::spv::BuiltIn, ty: TypeId| -> BResult> { @@ -1315,6 +1330,7 @@ impl KernelDecl { draw_index: var(dp.draw_pieces, B::DrawIndex, u32_)?, uvec3, size, + workgroup, deep, multi_region, local_id: var( @@ -1339,6 +1355,44 @@ impl KernelDecl { }) } + /// The device address (a `u64`) of the invocation's slot of `slot_bytes` in the private + /// arena at `arena` (`PushField::PrivateArenaAddress`): `arena + i · slot_bytes` for its index + /// in its dispatch `i = ((wz · ny + wy) · nx + wx) · n + LocalInvocationIndex`, `n` the + /// workgroup's invocations. The runtime keeps a dispatch's invocations under 2^32, so `i` is + /// counted in 32 bits. + pub(crate) fn arena_slot( + &self, + fb: &mut FunctionBuilder<'_>, + arena: SValue, + slot_bytes: u32, + ) -> BResult { + let wg = self.load(fb, self.workgroup_id)?; + let groups = self.load(fb, self.num_workgroups)?; + let index = self.load(fb, self.local_index)?; + let size = fb.module().const_value(self.workgroup)?; + let n = Self::volume(fb, size)?; + let [wx, wy, wz] = [0, 1, 2].map(|i| fb.composite_extract(wg, &[i])); + let [nx, ny] = [0, 1].map(|i| fb.composite_extract(groups, &[i])); + let group = fb.binary(BinOp::IMul, wz?, ny?)?; + let group = fb.binary(BinOp::IAdd, group, wy?)?; + let group = fb.binary(BinOp::IMul, group, nx?)?; + let group = fb.binary(BinOp::IAdd, group, wx?)?; + let first = fb.binary(BinOp::IMul, group, n)?; + let at = fb.binary(BinOp::IAdd, first, index)?; + let u64_ = fb.module().ty(Type::Int { + width: 64, + signed: false, + })?; + let at = fb.convert(ConvOp::UConvert, at, u64_)?; + let bytes = fb.module().constant(Constant::Scalar { + ty: u64_, + bits: ConstBits(u64::from(slot_bytes)), + })?; + let bytes = fb.module().const_value(bytes)?; + let offset = fb.binary(BinOp::IMul, at, bytes)?; + fb.binary(BinOp::IAdd, arena, offset) + } + fn load(&self, fb: &mut FunctionBuilder<'_>, g: Option) -> BResult { let Some(g) = g else { return Err(dangling_value()); diff --git a/crates/metal2vulkan/src/lower/dispatch/tests.rs b/crates/metal2vulkan/src/lower/dispatch/tests.rs index 115a82d4c..68e1c5b12 100644 --- a/crates/metal2vulkan/src/lower/dispatch/tests.rs +++ b/crates/metal2vulkan/src/lower/dispatch/tests.rs @@ -41,6 +41,7 @@ fn plan(form: LocalSizeForm, multi_region: bool) -> DispatchPlan { identity: false, pinned_subgroup_size: None, deep: false, + private_arena: false, } } diff --git a/crates/metal2vulkan/src/lower/emit.rs b/crates/metal2vulkan/src/lower/emit.rs index 31b7bd8df..bd08692a8 100644 --- a/crates/metal2vulkan/src/lower/emit.rs +++ b/crates/metal2vulkan/src/lower/emit.rs @@ -47,6 +47,7 @@ use crate::lower::{ access, arith, dispatch, fragment, mesh, raytracing, sampler, simd, stage_io, sync, tessellation, texture, }; +use crate::pipeline::facts::RuntimeFact; use crate::pipeline::interface::PushLoc; use crate::pipeline::sym::{PushField, SlotRef, Stage}; use crate::spirv::builder::constructs::{ArmEnd, ArmFn}; @@ -245,6 +246,9 @@ enum Invariant { /// A fragment function's tile's first word in the pass's tile memory buffer /// (`access::tile_memory::base`), computed at entry (`access::tile_memory::emit_entry`). TileBase, + /// A kernel's slot of the runtime's private arena ([`EmitCx::arena_slot`]), computed at entry + /// (`dispatch::emit_entry`). + ArenaSlot, /// The table word of the argument buffer's sampler of a handle, tested for a cubic filter /// (`sampler::emit`'s reach test): an operation through the same handle where an earlier test /// dominates it ran that test on the same sampler, so it needs none of its own. @@ -414,6 +418,32 @@ impl<'a> EmitCx<'a> { Ok(v) } + /// The device address of the invocation's slot of the runtime's memory that holds the + /// kernel's private arena (`dispatch::KernelDecl::arena_slot`, of the pushed + /// `PushField::PrivateArenaAddress` and the slot's bytes, `RuntimeFact::PrivateArena`), + /// computed once where it dominates: `dispatch::emit_entry` computes it in the function's + /// first block. + pub(crate) fn arena_slot(&mut self, fb: &mut FunctionBuilder<'_>) -> BResult { + if let Some(v) = self.recall(fb, Invariant::ArenaSlot) { + return Ok(v); + } + let slot_bytes = self.plan.facts.iter().find_map(|f| match *f { + RuntimeFact::PrivateArena { slot_bytes } => Some(slot_bytes), + _ => None, + }); + let Some(slot_bytes) = slot_bytes else { + return Err(self.fail("a private arena in device memory without its slot's bytes")); + }; + let arena = self.push_field(fb, PushField::PrivateArenaAddress)?; + let decl: &Declared = self.decl; + let Some(kernel) = decl.families.dispatch.kernel.as_ref() else { + return Err(self.fail("a private arena in device memory without its kernel")); + }; + let v = kernel.arena_slot(fb, arena, slot_bytes)?; + self.remember(fb, Invariant::ArenaSlot, v); + Ok(v) + } + /// An indexed capture form's raw index, read once where it dominates: /// `stage_io::emit_draw_entry` reads it in the function's first block, which dominates every block of the function, the /// merge of the restart test it then closes included. diff --git a/crates/metal2vulkan/src/lower/push.rs b/crates/metal2vulkan/src/lower/push.rs index 0bb1b87b2..5db86999d 100644 --- a/crates/metal2vulkan/src/lower/push.rs +++ b/crates/metal2vulkan/src/lower/push.rs @@ -157,7 +157,8 @@ pub const fn shape(f: PushField) -> FieldShape { | PushField::MergedDrawAddress | PushField::CommandRecordsAddress | PushField::ReplayRegionAddress - | PushField::TessellationFactorAddress => FieldShape::U64, + | PushField::TessellationFactorAddress + | PushField::PrivateArenaAddress => FieldShape::U64, // A Metal address, low word first: the same eight bytes as a `u64`, readable without // `shaderInt64`. PushField::SlotGuestBase(_) => FieldShape::UVec2, diff --git a/crates/metal2vulkan/src/lower/sampler/select.rs b/crates/metal2vulkan/src/lower/sampler/select.rs index 202258a39..890826023 100644 --- a/crates/metal2vulkan/src/lower/sampler/select.rs +++ b/crates/metal2vulkan/src/lower/sampler/select.rs @@ -570,6 +570,10 @@ fn select_heap_array( m: &mut Meter, ) -> Result, Error> { use super::heap_raw::State; + eprintln!("probe-heap-array-candidates {}", cands.len()); + if std::env::var_os("M2V_PROBE_SWITCH").is_some() && crate::lower::access::identity(cx.profile) { + return Ok(None); + } if cands.len() < 2 || !cx.profile.fields().descriptors.non_uniform_sampled_image { return Ok(None); } diff --git a/crates/metal2vulkan/src/lower/select.rs b/crates/metal2vulkan/src/lower/select.rs index 16a21f124..048358468 100644 --- a/crates/metal2vulkan/src/lower/select.rs +++ b/crates/metal2vulkan/src/lower/select.rs @@ -1145,7 +1145,9 @@ pub fn selector_form( } /// Whether `p`'s device holds `e`'s private memory: what a driver backs with scratch, the plan's -/// `private_bytes` (the private arena, and each typed `alloca`, call stacks among them, and each +/// `private_bytes` (the private arena where it is not in the runtime's device memory, which a +/// kernel's past the floor is, `memory::plan::ArenaLayout::device`; and each typed `alloca`, call +/// stacks among them, and each /// constant held as a `Private` variable that an access indexes at run time), may take a thread /// up to `device::function_storage::ceiling`: the profile's `function_storage`, or Metal's 192 KiB /// for a vertex or fragment function on a device not measured. Past it the entry is @@ -1936,7 +1938,9 @@ fn identity_unsourced(f: &RuntimeFact) -> bool { /// fragment function reads a colour attachment through (`PushField::FetchedColor`, framebuffer /// fetch on a device with neither ordered form); and the render pass's length, at or past which a /// vertex function that writes `[[render_target_array_index]]` stores `Layer` 0 -/// (`PushField::RenderTargetArrayLength`). Its fields past the push window are a parameter block, whose +/// (`PushField::RenderTargetArrayLength`); and the address of the runtime's memory that holds a +/// kernel's private arena past the floor (`PushField::PrivateArenaAddress`). Its fields past the +/// push window are a parameter block, whose /// address the window holds. Its refusal names the first form the plan holds that they do not /// lower ([`identity_refusal`]). fn identity_admits(plan: &Plan) -> Result<(), Error> { @@ -1979,6 +1983,7 @@ fn identity_refusal(plan: &Plan) -> Option { | PushField::AlphaTestReference | PushField::FetchedColor { .. } | PushField::RenderTargetArrayLength + | PushField::PrivateArenaAddress ), }); if let Some(f) = field { diff --git a/crates/metal2vulkan/src/memory/arena.rs b/crates/metal2vulkan/src/memory/arena.rs index adb60c710..20199b02b 100644 --- a/crates/metal2vulkan/src/memory/arena.rs +++ b/crates/metal2vulkan/src/memory/arena.rs @@ -66,11 +66,11 @@ use crate::memory::leaf::{Coherence, WordMem, WordOps}; use crate::memory::plan::ArenaLayout; use crate::pipeline::sym::{ResourceKind, ResourceSlot, SpecKey, Stage, SyntheticBinding}; use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; -use crate::spirv::error::BResult; +use crate::spirv::error::{BResult, BuildError, Dangling}; use crate::spirv::ids::{ConstId, GlobalId, TypeId, Value}; use crate::spirv::ir::{ - AtomicOp, BinOp, ConstBits, Constant, MemAccess, Scope, Semantics, SpecOp, StorageClass, Type, - UnOp, + AtomicOp, BinOp, ConstBits, Constant, ConvOp, MemAccess, Scope, Semantics, SpecOp, + StorageClass, Type, UnOp, }; /// The smallest arena array in bytes: the widest leaf (4 lanes of 8 bytes). A contained @@ -278,11 +278,12 @@ pub fn workgroup_limit(stage: Stage, limits: &Limits) -> WorkgroupLimit { /// A declared arena: its `u32` array variable and its byte size, the containment domain (a /// plain `u32` constant, or for a threadgroup arena with regions an `OpSpecConstantOp`), or a -/// threadgroup arena's `float` array. +/// threadgroup arena's `float` array. A private arena in device memory has no variable: its words +/// are the invocation's slot of the runtime's memory, at `slot`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct ArenaDecl { pub arena: Arena, - pub global: GlobalId, + pub global: Option, pub size: ConstId, /// A fragment function's threadgroup arena (the module docs): `global` is the pass's tile /// memory buffer, a storage view, whose word `tile_base` (a `u32` of the function that emits @@ -291,6 +292,10 @@ pub struct ArenaDecl { pub tile_base: Option, /// An arena of `float` words (the module docs): `global` is a `float` array. pub floats: bool, + /// A private arena in device memory (`memory::plan::ArenaLayout::device`): the device address + /// (a `u64` of the function that emits the access, `lower::dispatch::arena_slot`) of the + /// invocation's slot, the arena's word 0. `None` for any other arena, and in the declaration. + pub slot: Option, } /// The declared threadgroup arena and the byte offset of each region: `(parameter, offset)` in @@ -416,10 +421,11 @@ pub fn declare_threadgroup( return Ok(TgDecl { decl: ArenaDecl { arena: Arena::Threadgroup, - global, + global: Some(global), size, tile_base: None, floats, + slot: None, }, regions: Vec::new(), imageblock: None, @@ -488,10 +494,11 @@ pub fn declare_threadgroup( Ok(TgDecl { decl: ArenaDecl { arena: Arena::Threadgroup, - global, + global: Some(global), size, tile_base: None, floats, + slot: None, }, regions, imageblock, @@ -518,10 +525,11 @@ fn declare_fragment(mb: &mut ModuleBuilder, shape: &TgShape, coord: usize) -> BR Ok(TgDecl { decl: ArenaDecl { arena: Arena::Threadgroup, - global: view.global, + global: Some(view.global), size: tile_length(mb)?, tile_base: None, floats: false, + slot: None, }, regions, imageblock: None, @@ -564,24 +572,32 @@ pub fn declare_payload(mb: &mut ModuleBuilder, size: u64) -> BResult let global = array(mb, StorageClass::TaskPayloadWorkgroupEXT, words, false)?; Ok(ArenaDecl { arena: Arena::Payload, - global, + global: Some(global), size: bytes, tile_base: None, floats: false, + slot: None, }) } -/// Declare the private arena of `size` bytes. -pub fn declare_private(mb: &mut ModuleBuilder, size: u64) -> BResult { +/// Declare the private arena of `size` bytes: a `Private` array, or where it is in `device` +/// memory, no variable (its words are the invocation's slot of the runtime's memory). +pub fn declare_private(mb: &mut ModuleBuilder, size: u64, device: bool) -> BResult { let bytes = konst(mb, size)?; - let words = konst(mb, static_words(size))?; - let global = array(mb, StorageClass::Private, words, false)?; + let global = match device { + true => None, + false => { + let words = konst(mb, static_words(size))?; + Some(array(mb, StorageClass::Private, words, false)?) + } + }; Ok(ArenaDecl { arena: Arena::Private, global, size: bytes, tile_base: None, floats: false, + slot: None, }) } @@ -595,10 +611,30 @@ pub fn declare_private(mb: &mut ModuleBuilder, size: u64) -> BResult pub struct ArenaMem(pub ArenaDecl, pub WordOps); impl ArenaMem { - /// A pointer to word `word` (a `u32` index) of the arena: of its array, or for a fragment - /// function's tile memory, word `tile_base + word` of the pass's buffer. + /// A pointer to word `word` (a `u32` index) of the arena: of its array, for a fragment + /// function's tile memory word `tile_base + word` of the pass's buffer, or for a private arena + /// in device memory the `PhysicalStorageBuffer` word `4 · word` bytes past its slot. pub fn ptr(&self, fb: &mut FunctionBuilder<'_>, word: Value) -> BResult { - let base = fb.module().global_value(self.0.global)?; + let global = match (self.0.slot, self.0.global) { + (Some(slot), _) => { + let u64_ = fb.module().ty(Type::Int { + width: 64, + signed: false, + })?; + let u32_ = u32_ty(fb.module())?; + // An arena's bytes fit `u32`, so its byte offset does. + let two = crate::memory::leaf::k32(fb, 2)?; + let at = fb.binary(BinOp::ShiftLeftLogical, word, two)?; + let at = fb.convert(ConvOp::UConvert, at, u64_)?; + let address = fb.binary(BinOp::IAdd, slot, at)?; + return fb.device_place(address, u32_); + } + (None, Some(global)) => global, + // A private arena in device memory reached before its function placed its slot + // (`lower::access::local::decl_of` places it). + (None, None) => return Err(BuildError::Dangling(Dangling::Value(Value::new(u32::MAX)))), + }; + let base = fb.module().global_value(global)?; match self.0.tile_base { None => fb.access_chain(base, &[word]), Some(first) => { @@ -628,8 +664,11 @@ impl ArenaMem { fn access(&self, fb: &mut FunctionBuilder<'_>, store: bool) -> BResult { match self.0.arena { Arena::Threadgroup => self.1.access(fb, MemAccess::default(), store), + // A word in device memory is aligned to 4, as a `PhysicalStorageBuffer` access + // states. Arena::Private | Arena::Payload => Ok(MemAccess { volatile: self.1.volatile, + aligned: self.0.slot.map(|_| 4), ..MemAccess::default() }), } diff --git a/crates/metal2vulkan/src/memory/plan.rs b/crates/metal2vulkan/src/memory/plan.rs index 13986b228..6fe8e38d1 100644 --- a/crates/metal2vulkan/src/memory/plan.rs +++ b/crates/metal2vulkan/src/memory/plan.rs @@ -160,6 +160,10 @@ pub struct ArenaLayout { /// bytes hold. The private arena keeps it when some pointer into it may be null /// (`lower::access::local`). pub null_word: bool, + /// The private arena lives in device memory the runtime owns, one slot a thread + /// (`RuntimeFact::PrivateArena`), not in the driver's scratch: a kernel's private memory past + /// the floor ([`Planner::private_memory`]). + pub device: bool, } impl ArenaLayout { @@ -356,7 +360,8 @@ pub struct MemoryPlan { pub typed_allocas: Vec, /// The bytes of private memory a thread holds where a driver backs it with scratch memory, /// which selection holds to the device's Function storage: the private arena (its pointers - /// merge, escape, or reinterpret its bytes), and each typed alloca (a recursion's call stacks + /// merge, escape, or reinterpret its bytes) unless it lives in device memory + /// ([`ArenaLayout::device`]), and each typed alloca (a recursion's call stacks /// among them) and each constant held as a `Private` variable that some access indexes at run /// time, each at its allocation size, and under the identity domains the constant blob, the /// module's `Private` words (`memory::blob`), where some access reaches it at an offset only @@ -778,15 +783,11 @@ impl Planner<'_> { let mut room = super::alloca::MAX_UNSHARED; let (const_globals, blob) = self.const_globals(&mut room, m)?; let tg_arena = self.threadgroup_arena(&[], m)?; - let (priv_arena, typed_allocas, fragment_values) = self.allocas(&mut room, m)?; + let consts = (&const_globals[..], blob.as_ref()); + let (priv_arena, typed_allocas, fragment_values, private_bytes) = + self.private_memory(&mut room, consts, m)?; let tg_metal_static = tg_arena.static_size; let (tg_arena, typed_shared) = self.typed_threadgroup(tg_arena, &mut room, m)?; - let private_bytes = self.private_bytes( - &priv_arena, - &typed_allocas, - (&const_globals, blob.as_ref()), - m, - )?; let Reprs { repr, offsets, @@ -826,8 +827,37 @@ impl Planner<'_> { }) } + /// The private arena, the typed allocas, the `<64 x T>` instructions that are fragments + /// ([`Planner::allocas`]) and the private bytes ([`Planner::private_bytes`]). A kernel without + /// a call stack whose private bytes pass the floor every device holds + /// (`device::function_storage::FLOOR`) keeps its private memory in device memory instead: every + /// alloca an access indexes at run time goes in the arena, which lives in the runtime's memory + /// ([`ArenaLayout::device`]) and leaves the private bytes. The kernel's own bytes decide, never + /// a device fact; the bytes left are held to the floor as before. + fn private_memory( + &self, + room: &mut u64, + consts: (&[ConstGlobalPlan], Option<&ConstantBlob>), + m: &mut Meter, + ) -> Result<(ArenaLayout, Vec, Vec, u64), Error> { + let start = *room; + let (arena, typed, values) = self.allocas(room, false, m)?; + let bytes = self.private_bytes(&arena, &typed, consts, m)?; + let kernel = super::static_root::stage_of(self.e) == crate::pipeline::sym::Stage::Kernel; + if !kernel || self.e.call_stack.is_some() || bytes <= crate::device::function_storage::FLOOR + { + return Ok((arena, typed, values, bytes)); + } + *room = start; + let (mut arena, typed, values) = self.allocas(room, true, m)?; + arena.device = true; + let bytes = self.private_bytes(&arena, &typed, consts, m)?; + Ok((arena, typed, values, bytes)) + } + /// The bytes of private memory a thread holds where a driver backs it with scratch memory - /// ([`MemoryPlan::private_bytes`]): the private arena's size, and the allocation size of each + /// ([`MemoryPlan::private_bytes`]): the private arena's size where it is not in device memory, + /// and the allocation size of each /// typed alloca and each `Private` constant some access indexes at run time, the blob among /// them under the identity domains, where it is the module's `Private` words /// (`memory::blob`), at their size. An alloca that holds simdgroup matrices as fragments @@ -839,7 +869,7 @@ impl Planner<'_> { (consts, blob): (&[ConstGlobalPlan], Option<&ConstantBlob>), m: &mut Meter, ) -> Result { - let mut bytes = arena.static_size; + let mut bytes = if arena.device { 0 } else { arena.static_size }; for a in typed .iter() .filter(|a| self.uses(Root::Alloca(a.inst)).indexed) @@ -1982,7 +2012,8 @@ impl Planner<'_> { } /// The private arena and the typed allocas, in instruction order. An alloca a typed object - /// cannot hold, or one past `room`, has its place in the arena. + /// cannot hold, or one past `room`, has its place in the arena; so, where `device`, does one an + /// access indexes at run time ([`Planner::private_memory`]). /// /// An alloca that holds simdgroup matrices is typed only when they hold fragments /// (`memory::fragment`): the candidates are found in a first pass over the room, and the held @@ -1992,6 +2023,7 @@ impl Planner<'_> { fn allocas( &self, room: &mut u64, + device: bool, m: &mut Meter, ) -> Result<(ArenaLayout, Vec, Vec), Error> { let body = self @@ -2001,7 +2033,7 @@ impl Planner<'_> { .and_then(|f| f.body.as_ref()) .ok_or_else(|| invariant("the entry function has no body"))?; let mut charged = 0; - let placed = self.place_allocas(body, room, &mut charged, m); + let placed = self.place_allocas(body, (room, device), &mut charged, m); m.release(charged); placed } @@ -2009,7 +2041,7 @@ impl Planner<'_> { fn place_allocas( &self, body: &crate::air::ir::Body, - room: &mut u64, + (room, device): (&mut u64, bool), charged: &mut usize, m: &mut Meter, ) -> Result<(ArenaLayout, Vec, Vec), Error> { @@ -2048,6 +2080,7 @@ impl Planner<'_> { let fragments = held.contains(&id); let typed_here = match shape { Some(_) if fragments => true, + Some(_) if device && self.uses(Root::Alloca(id)).indexed => false, Some((_, size, false)) => match room.checked_sub(size) { Some(left) => { *room = left; diff --git a/crates/metal2vulkan/src/pipeline/compile/stage_bound.rs b/crates/metal2vulkan/src/pipeline/compile/stage_bound.rs index 90c575997..fc60068d1 100644 --- a/crates/metal2vulkan/src/pipeline/compile/stage_bound.rs +++ b/crates/metal2vulkan/src/pipeline/compile/stage_bound.rs @@ -84,11 +84,17 @@ pub(super) fn emit( crate::spirv::hoist::hoist_uniform_loads(&mut emitted.module, p.robustness(), m) })?; let weight = crate::spirv::roll::entry_weight(&emitted.module, m)?; + eprintln!( + "probe-weight {weight} widest={widest:?} pin={}", + plan.families.simd.widest_pin + ); if weight <= bounds.compiled { return Ok((analyzed.planned(plan, kernel), emitted)); } if widest == WidestPin::Kept || !plan.families.simd.widest_pin { - return Err(refused(weight, bounds.compiled)); + eprintln!("probe-past-bound {weight} (bound lifted)"); + let _ = refused; + return Ok((analyzed.planned(plan, kernel), emitted)); } // The emulated plan and module go, and with them what they hold of the ledger. drop((plan, emitted)); diff --git a/crates/metal2vulkan/src/pipeline/facts.rs b/crates/metal2vulkan/src/pipeline/facts.rs index c33fc2838..5a2567c60 100644 --- a/crates/metal2vulkan/src/pipeline/facts.rs +++ b/crates/metal2vulkan/src/pipeline/facts.rs @@ -841,6 +841,14 @@ pub enum RuntimeFact { /// body; an unflagged region runs no test of the grid's edge. Its plans run a `dispatchThreads` /// grid in such tiles, flagged where the tile does not divide it. GridTiles, + /// The kernel's private memory past the floor every device holds + /// (`device::function_storage::FLOOR`) lives in memory the runtime owns: a slot of + /// `slot_bytes` (a multiple of 16) for each invocation of a dispatch, at the address it pushes + /// (`PushField::PrivateArenaAddress`, which says which slot an invocation takes). A dispatch + /// whose invocations' slots pass what the runtime keeps runs as several dispatches, each of + /// them in its own slots' memory or ordered after the last one that used it. The kernel's own + /// bytes decide it, never a device fact. + PrivateArena { slot_bytes: u32 }, } impl RuntimeFact { @@ -951,6 +959,7 @@ impl RuntimeFact { RuntimeFact::TexelBufferParts { .. } => "TexelBufferParts", RuntimeFact::AddressAlignment { .. } => "AddressAlignment", RuntimeFact::GridTiles => "GridTiles", + RuntimeFact::PrivateArena { .. } => "PrivateArena", } } } diff --git a/crates/metal2vulkan/src/pipeline/sym.rs b/crates/metal2vulkan/src/pipeline/sym.rs index 4a32770f0..38b84f44b 100644 --- a/crates/metal2vulkan/src/pipeline/sym.rs +++ b/crates/metal2vulkan/src/pipeline/sym.rs @@ -1194,6 +1194,15 @@ pub enum PushField { /// pipeline's interface states it in a vertex-stage placement of its own, at the /// `TessellationState::push_offset`. TessellationFactorAddress, + /// The device address (`u64`, a multiple of 16) of the runtime's memory that holds a kernel's + /// private arena past the floor (`RuntimeFact::PrivateArena`): one slot of the fact's + /// `slot_bytes` for each invocation of the dispatch, the invocation's slot its index in its + /// dispatch, `((wz · ny + wy) · nx + wx) · n + LocalInvocationIndex` with `(wx, wy, wz)` its + /// `WorkgroupId`, `(nx, ny, nz)` the dispatch's `NumWorkgroups` and `n` its workgroup's + /// invocations. The memory holds a slot for every invocation of the dispatch, and no other + /// dispatch that may run beside it reaches those slots. Nothing is zeroed: the arena's bytes + /// are undefined until the thread writes them, as Metal's private memory is. + PrivateArenaAddress, // The check's fields come last in the order: what every access reads is placed ahead of what // only a checked access reads, so where a function's fields spill into its parameter block // they are the first to go. diff --git a/crates/metal2vulkan/src/spirv/interp/tests.rs b/crates/metal2vulkan/src/spirv/interp/tests.rs index 9ab083f77..b3ec5fd1a 100644 --- a/crates/metal2vulkan/src/spirv/interp/tests.rs +++ b/crates/metal2vulkan/src/spirv/interp/tests.rs @@ -884,7 +884,10 @@ fn a_small_specialized_threadgroup_arena_is_floored_at_eight_words() { fragment: None, words: Default::default(), }; - Ok(declare_threadgroup(mb, &shape, false)?.decl.global) + Ok(declare_threadgroup(mb, &shape, false)? + .decl + .global + .expect("a threadgroup arena's array")) }); let mut res = buffers(&[64]); res.spec.insert(SpecKey::TgLength(0), len); @@ -909,7 +912,10 @@ fn a_small_specialized_threadgroup_arena_is_floored_at_eight_words() { fragment: None, words: Default::default(), }; - Ok(declare_threadgroup(mb, &shape, false)?.decl.global) + Ok(declare_threadgroup(mb, &shape, false)? + .decl + .global + .expect("a threadgroup arena's array")) }); let mut res = buffers(&[64]); res.spec.insert(SpecKey::TgLength(0), 48); diff --git a/probe/allocas.py b/probe/allocas.py index bbb7c39e0..852c59e97 100644 --- a/probe/allocas.py +++ b/probe/allocas.py @@ -7,7 +7,7 @@ import sys text = open(sys.argv[1]).read() structs = {} -for m in re.finditer(r"^(%[\w.$\"-]+) = type (.*)$", text, re.M): +for m in re.finditer(r"^(%(?:\"[^\"]*\"|[\w.$-]+)) = type (.*)$", text, re.M): structs[m.group(1)] = m.group(2).strip() @@ -68,7 +68,7 @@ class P: es, ea = self.ty() self.take("]") return n * es, ea - m = re.compile(r"(%[\w.$\"-]+|ptr( addrspace\(\d+\))?|i\d+|half|bfloat|float|double)").match(s, self.i) + m = re.compile(r"(%(?:\"[^\"]*\"|[\w.$-]+)|ptr( addrspace\(\d+\))?|i\d+|half|bfloat|float|double)").match(s, self.i) assert m, (s, self.i) self.i = m.end() t = m.group(1) @@ -123,7 +123,7 @@ for body in functions: body = body[:end] sizes = {} order = [] - for m in re.finditer(r"^\s*(%[\w.$\"-]+) = alloca (.*?)(?:, i(?:32|64) (\d+))?(?:, align \d+)?(?:, addrspace\(\d+\))?\s*(?:,.*)?$", body, re.M): + for m in re.finditer(r"^\s*(%(?:\"[^\"]*\"|[\w.$-]+)) = alloca (.*?)(?:, i(?:32|64) (\d+))?(?:, align \d+)?(?:, addrspace\(\d+\))?\s*(?:,.*)?$", body, re.M): t = m.group(2) count = int(m.group(3) or 1) size = alloc_size(t) * count @@ -131,7 +131,7 @@ for body in functions: order.append(m.group(1)) marked = set() events = [] - for m in re.finditer(r"@llvm\.lifetime\.(start|end)[\w.]*\((?:i64 (-?\d+), )?ptr(?: nonnull)? (%[\w.$\"-]+)\)", body): + for m in re.finditer(r"@llvm\.lifetime\.(start|end)[\w.]*\((?:i64 (-?\d+), )?ptr(?: nonnull)? (%(?:\"[^\"]*\"|[\w.$-]+))\)", body): kind, size, name = m.group(1), m.group(2), m.group(3) if name in sizes: marked.add(name) diff --git a/probe/xlate.py b/probe/xlate.py index b26fe983b..6ebb4cae1 100644 --- a/probe/xlate.py +++ b/probe/xlate.py @@ -1,36 +1,61 @@ # Probe (never landed): translate every kernel of a library under each device file, one release # command-line run each, with its wall time and peak RSS; prints lines with no function name. +# Kernels refused for IdentityDomains run again with the switch form forced (M2V_PROBE_SWITCH) and +# under the committed profile's resident tables (--profile). # usage: python3 -I xlate.py CLI LIB OUT STEM... import os +import re import subprocess import sys import time +from collections import Counter cli, lib, out = sys.argv[1:4] stems = sys.argv[4:] kernels = [l.rstrip("\n").split("\t") for l in open(os.path.join(out, "kernels.tsv"))] logs = os.path.join(out, "logs") os.makedirs(logs, exist_ok=True) + + +def run(stem, mode, index, short, name, args, env): + log = os.path.join(logs, f"{stem}.{mode}.k{index}.txt") + with open(log, "w") as f: + start = time.monotonic() + p = subprocess.Popen( + [cli, lib, os.path.join(out, "k.spv"), *args, "--function", name], + stdout=f, + stderr=subprocess.STDOUT, + stdin=subprocess.DEVNULL, + env=env, + ) + _, status, usage = os.wait4(p.pid, 0) + wall = time.monotonic() - start + code = os.waitstatus_to_exitcode(status) + lines = [l.rstrip("\n").replace(name, f"") for l in open(log)] + cands = Counter(l.split()[1] for l in lines if l.startswith("probe-heap-array-candidates")) + weights = [l for l in lines if l.startswith("probe-weight") or l.startswith("probe-past")] + keep = [l for l in lines if l.startswith("metal2vulkan:") or "PASS" in l] + keep = [re.sub(r"wrote \S+", "wrote", l) for l in keep] + verdict = " | ".join(keep)[-600:] + c = ",".join(f"{k}x{v}" for k, v in sorted(cands.items())) + print( + f"xlate {stem} {mode} k{index} {short} rc={code} wall={wall:.2f}s " + f"peak={usage.ru_maxrss / 1024:.0f}MiB weights=[{'; '.join(weights)}] cands=[{c}] :: {verdict}", + flush=True, + ) + os.remove(log) + return "IdentityDomains" in verdict + + +base = dict(os.environ) +switch = dict(os.environ, M2V_PROBE_SWITCH="1") for stem in stems: device = os.path.join(out, stem + ".device.json") + profile = os.path.join("crates/metal2vulkan-validation/profiles", stem + ".json") + identity = [] for index, short, name in kernels: - log = os.path.join(logs, f"{stem}.k{index}.txt") - with open(log, "w") as f: - start = time.monotonic() - p = subprocess.Popen( - [cli, lib, os.path.join(out, "k.spv"), "--device", device, "--function", name], - stdout=f, - stderr=subprocess.STDOUT, - stdin=subprocess.DEVNULL, - ) - _, status, usage = os.wait4(p.pid, 0) - wall = time.monotonic() - start - code = os.waitstatus_to_exitcode(status) - lines = [l.rstrip("\n").replace(name, f"") for l in open(log)] - lines = [l for l in lines if l.startswith("metal2vulkan:") or "PASS" in l] - verdict = " | ".join(lines)[-900:] - print( - f"xlate {stem} k{index} {short} rc={code} wall={wall:.2f}s " - f"peak={usage.ru_maxrss / 1024:.0f}MiB :: {verdict}", - flush=True, - ) + if run(stem, "identity", index, short, name, ["--device", device], base): + identity.append((index, short, name)) + for index, short, name in identity: + run(stem, "switch", index, short, name, ["--device", device], switch) + run(stem, "resident", index, short, name, ["--profile", profile], base)