diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 3c1a12df9..2a34e4fae 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -94,6 +94,14 @@ them over this crate's items: `Device::with_present_queue` runs the consumer's presents on the presenting queue under its lock (see "Presenting"). The runtime keeps owning every handle. - `Device::has_unified_memory` is true where Vulkan's device type is integrated or CPU. +- `Device::max_threadgroup_memory_length` answers `maxThreadgroupMemoryLength`: the device's + `maxComputeSharedMemorySize` less the 4-byte vote word a kernel's partial-threadgroups variant + may take beside its threadgroup memory, rounded down to 16, and at most Metal's 32,768. A kernel + whose threadgroup memory, its own and the lengths set, is within it runs every dispatch, ragged + grids included. On a device of 32,768 bytes it is 32,752, where a Mac reads 32,768. Every + dispatch is still checked against the device's own limit, so one past the answer and within + that limit runs as before. Unaudited: a guest that rounds the answer down to a power of two + gets 16 KiB there, where a Mac's answer gives it 32 KiB. - `Device::supports_function_pointers` is true on every device: a kernel's call through a visible-function table is a switch over the functions its state links, known when the state is made, and needs no Vulkan feature (see "Visible-function tables"). The runtime gives no @@ -2387,8 +2395,9 @@ while the driver's exit handler waited on a lock, with every runtime thread alre makes, is in docs/API.md, section 5 (`PushField::SlotBounds`). - A dispatch's threadgroup memory, the kernel's own and the lengths set, each rounded up to 16 bytes, is at most the device's `maxComputeSharedMemorySize` (`Limit::ThreadgroupMemory`), where - Metal's is its `maxThreadgroupMemoryLength`. A kernel's access past its threadgroup memory is - undefined, as in Metal, and the runtime does not confine it. + Metal's is its `maxThreadgroupMemoryLength`, which `Device::max_threadgroup_memory_length` + answers with room for a partial threadgroup's vote word. A kernel's access past its threadgroup + memory is undefined, as in Metal, and the runtime does not confine it. - Threadgroup memory, a function's declared threadgroup variables and its `[[threadgroup(n)]]` arguments, reads zero in every threadgroup until the program writes it, as an Apple GPU reads it (the translator's null initializers, docs/API.md, "Threadgroup memory before the program writes @@ -3530,7 +3539,11 @@ cache is answered compile-required on both. device's compute subgroups are neither 32 lanes nor 64 or 128 split into 32-lane clusters. 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 - `maxComputeSharedMemorySize`. + `maxComputeSharedMemorySize`, which `Device::max_threadgroup_memory_length` leaves room for: a + kernel that takes more threadgroup memory than that answer, as one built for a Mac's 32,768 + bytes does on a device of 32,768, keeps this refusal for its ragged grids. The answer does not + count an emulated SIMD group's scratch, whose bytes vary by kernel, so a kernel at the answer + whose SIMD groups are emulated can still pass the device's limit (`Limit::ThreadgroupMemory`). - A kernel that observes its threadgroup partition makes a `VkPipeline` per threadgroup size it is dispatched at: the state's main pipeline at the descriptor's `requiredThreadsPerThreadgroup` where the kernel takes no threadgroup memory length from the diff --git a/crates/metal2vulkan-runtime/src/device.rs b/crates/metal2vulkan-runtime/src/device.rs index 3dd130afb..d35f3989d 100644 --- a/crates/metal2vulkan-runtime/src/device.rs +++ b/crates/metal2vulkan-runtime/src/device.rs @@ -18,7 +18,7 @@ use crate::instance::{Instance, PhysicalDevice}; use crate::kernel_map::KernelMap; use crate::memory::{self, BlockId, BlockMappings, Memory, MemoryClass, Pool}; use crate::pass::ResolveModes; -use crate::pipeline::PUSH_STAGES; +use crate::pipeline::{PUSH_STAGES, VOTE_BYTES}; use crate::places::Places; use crate::reaper::{self, Job, Reaper}; use crate::record::Recorders; @@ -393,6 +393,10 @@ pub(crate) struct Core { _live: Live, } +/// Metal's `maxThreadgroupMemoryLength` on Apple's GPUs: 32 KiB, the most +/// [`Device::max_threadgroup_memory_length`] answers. +const METAL_THREADGROUP_MEMORY: u32 = 32 * 1024; + /// No stop has begun. const RUNNING: u8 = 0; /// A stop is running. @@ -925,6 +929,20 @@ impl Device { self.shared.core.unified_memory } + /// `maxThreadgroupMemoryLength`: the device's `maxComputeSharedMemorySize` less the 4-byte + /// vote word a kernel's partial-threadgroups variant may take beside its threadgroup memory, + /// rounded down to 16, and at most Metal's 32 KiB. A kernel whose threadgroup memory, its own + /// and the lengths set, is within this answer runs its every dispatch, ragged grids included. + /// On a device of 32,768 bytes it is 32,752, where a Mac answers 32,768. It changes only the + /// answer: every dispatch is still checked against the device's own limit + /// ([`Limit::ThreadgroupMemory`](crate::Limit::ThreadgroupMemory)), so one past this answer + /// and within that limit runs as before. An emulated SIMD group's scratch, which varies by + /// kernel, is not counted (the crate's README, known gaps). + pub fn max_threadgroup_memory_length(&self) -> u32 { + let max = self.shared.core.limits.max_shared_memory; + (max.saturating_sub(VOTE_BYTES) / 16 * 16).min(METAL_THREADGROUP_MEMORY) + } + /// `supportsTextureSampleCount:`: whether `count` is a sample count the device renders into a /// colour and a depth attachment (its `framebufferColorSampleCounts` and /// `framebufferDepthSampleCounts`, of which Vulkan requires 1 and 4) that an Apple GPU takes: diff --git a/crates/metal2vulkan-runtime/src/pipeline.rs b/crates/metal2vulkan-runtime/src/pipeline.rs index b7daf2451..be50f26dd 100644 --- a/crates/metal2vulkan-runtime/src/pipeline.rs +++ b/crates/metal2vulkan-runtime/src/pipeline.rs @@ -150,6 +150,12 @@ impl DispatchVariant { /// (`ComputePipelineMetalInfo::metal_max_total_threads_per_threadgroup`). const METAL_MAX_THREADS: u32 = 1024; +/// The bytes of a predicated walk's vote word (`RuntimeFact::PredicationVote`), which a kernel's +/// partial-threadgroups variant takes beside its threadgroup memory ([`Memory::vote`]), and which +/// [`Device::max_threadgroup_memory_length`](crate::Device::max_threadgroup_memory_length) leaves +/// room for. +pub(crate) const VOTE_BYTES: u32 = 4; + /// The number the next [`Compiled`] takes: each content made has its own, never reused in the /// process, which a [`DispatchVariant`] names it by. static CONTENTS: AtomicU64 = AtomicU64::new(0); @@ -765,7 +771,7 @@ pub(crate) struct Interface { #[derive(Clone, Copy)] pub(crate) struct Memory { pub(crate) own: OwnMemory, - /// A predicated walk's vote word: 4 bytes, or 0. + /// A predicated walk's vote word: [`VOTE_BYTES`], or 0. pub(crate) vote: u32, } @@ -1644,7 +1650,7 @@ pub(crate) fn interface( align, } if align.is_power_of_two() => aligned.push((index, u64::from(align) - 1)), // The walk's vote word: 4 bytes beside the threadgroup memory. - RuntimeFact::PredicationVote => vote = 4, + RuntimeFact::PredicationVote => vote = VOTE_BYTES, // Each invocation's slot of the private arena, which the encoder places // (`FieldValue::PrivateArena`). RuntimeFact::PrivateArena { slot_bytes } => private_arena = Some(slot_bytes), diff --git a/crates/metal2vulkan-runtime/src/tests/translate.rs b/crates/metal2vulkan-runtime/src/tests/translate.rs index 5a5609096..45b88f318 100644 --- a/crates/metal2vulkan-runtime/src/tests/translate.rs +++ b/crates/metal2vulkan-runtime/src/tests/translate.rs @@ -4600,8 +4600,9 @@ $REGION_META!3 = !{i32 $OUT, !"air.buffer", !"air.location_index", i32 0, i32 1, /// [`SCAN`] at 1,024 threads, Metal's largest threadgroup, in its two shapes ([`scan_kernel`]): /// `scan_static`'s declared array and `scan_length`'s region the encoder sets, each of the /// bytes a guest is told for Metal's `maxThreadgroupMemoryLength`: Metal's own 32 KiB (or the - /// device's `maxComputeSharedMemorySize` where smaller), and `room`, the device's limit less - /// the predicated walk's 4-byte vote word, rounded down to 16 and at most 32 KiB. Each state's + /// device's `maxComputeSharedMemorySize` where smaller), and `room`, the device's answer + /// (`Device::max_threadgroup_memory_length`: its limit less the predicated walk's 4-byte vote + /// word, rounded down to 16 and at most 32 KiB, which the test checks). Each state's /// ragged grid of 25 threads, one partial threadgroup of 25, and its whole grid of 1,024 /// threads: at `room` every one runs and answers the program's inclusive sums, /// `(t + 1)(t + 2) / 2` for thread `t` of its threadgroup. At 32 KiB, where the bytes and the @@ -4612,12 +4613,17 @@ $REGION_META!3 = !{i32 $OUT, !"air.buffer", !"air.location_index", i32 0, i32 1, /// answer the sums. Each outcome is printed; the test fails on any other. #[test] fn every_device_runs_a_1024_thread_observers_ragged_grid_in_the_limit_less_its_vote_word() { - use crate::pipeline::Which; + use crate::pipeline::{Which, VOTE_BYTES}; each_device("compute_scan_at_the_told_limit", |name, _, device| { let limit = device.core().limits.max_shared_memory; let metal = limit.min(32 * 1024); - let room = ((limit - 4) / 16 * 16).min(32 * 1024); + let room = device.max_threadgroup_memory_length(); + assert_eq!( + room, + ((limit - VOTE_BYTES) / 16 * 16).min(32 * 1024), + "{name}: the answer, the limit less the vote word, rounded down to 16, at most 32 KiB" + ); let mut told = vec![metal]; if room != metal { told.push(room); @@ -4719,6 +4725,113 @@ $REGION_META!3 = !{i32 $OUT, !"air.buffer", !"air.location_index", i32 0, i32 1, }); } + /// A kernel of one barrier, in no loop, over its `[[threadgroup(0)]]` region: thread `t` stores + /// `t + 1` at word `t`, and past the barrier writes word `(t + 1) % n` to `out[g]`, `n` its + /// threadgroup's threads and `g` its position in the grid. It observes its threadgroup + /// partition, and its partial-threadgroups variant's predicated walk takes no vote word. + const NEIGHBOUR_LENGTH: &str = 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 @neighbour_length(ptr addrspace(3) %a, ptr addrspace(1) %out, i32 %t, i32 %g, <3 x i32> %size) { +entry: + %n = extractelement <3 x i32> %size, i64 0 + %pt = getelementptr inbounds i32, ptr addrspace(3) %a, i32 %t + %v = add i32 %t, 1 + store i32 %v, ptr addrspace(3) %pt, align 4 + tail call void @air.wg.barrier(i32 2, i32 1) + %nb = urem i32 %v, %n + %pn = getelementptr inbounds i32, ptr addrspace(3) %a, i32 %nb + %x = load i32, ptr addrspace(3) %pn, align 4 + %o = getelementptr inbounds i32, ptr addrspace(1) %out, i32 %g + store i32 %x, ptr addrspace(1) %o, align 4 + ret void +} + +declare void @air.wg.barrier(i32, i32) + +!air.kernel = !{!0} +!air.version = !{!8} +!air.language_version = !{!9} +!0 = !{ptr @neighbour_length, !1, !2} +!1 = !{} +!2 = !{!3, !4, !5, !6, !7} +!3 = !{i32 0, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 3, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"a"} +!4 = !{i32 1, !"air.buffer", !"air.location_index", i32 0, 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", !"out"} +!5 = !{i32 2, !"air.thread_index_in_threadgroup", !"air.arg_type_name", !"uint", !"air.arg_name", !"t"} +!6 = !{i32 3, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"g"} +!7 = !{i32 4, !"air.threads_per_threadgroup", !"air.arg_type_name", !"uint3", !"air.arg_name", !"size"} +!8 = !{i32 2, i32 8, i32 0} +!9 = !{!"Metal", i32 4, i32 0, i32 0} +"#; + + /// [`NEIGHBOUR_LENGTH`] at 1,024 threads with its region set at Metal's 32 KiB (the device's + /// `maxComputeSharedMemorySize` where smaller), past `Device::max_threadgroup_memory_length` + /// on a device of 32,768 bytes: the answer changes only what a guest is told, and a kernel + /// whose variant takes no vote word runs its ragged grid of 25 threads and its whole grid of + /// 1,024 within the device's own limit, each answering `(t + 1) % n + 1` for thread `t` of a + /// threadgroup of `n`. + #[test] + fn every_device_runs_a_kernel_without_a_vote_word_at_a_length_past_its_answer() { + use crate::pipeline::Which; + + let bitcode = match metal2vulkan_devtools::llvm_assemble_text(NEIGHBOUR_LENGTH) { + Ok(bitcode) => bitcode, + Err(AssembleError::Missing(why)) => { + eprintln!("SKIPPED: {why}"); + return; + } + Err(error) => panic!("neighbour_length: {error:?}"), + }; + let library = Library::from_air(&bitcode).expect("the library"); + let function = library.function("neighbour_length").expect("the kernel"); + let descriptor = ComputePipelineDescriptor::new(StageSource::Function( + FunctionDescriptor::new(function), + )); + each_device("compute_length_past_the_answer", |name, _, device| { + let limit = device.core().limits.max_shared_memory; + let length = limit.min(32 * 1024); + let answer = device.max_threadgroup_memory_length(); + let state = state(name, &device, &descriptor); + let compiled = &state.inner.compiled; + let partial = (compiled.variant_kernel(Which::Partial, |why| { + panic!("{name}: the partial-threadgroups variant is refused: {why:?}") + })) + .unwrap_or_else(|error| panic!("{name}: {error}")); + assert_eq!(partial.interface.memory.vote, 0, "{name}: no vote word"); + let queue = device.new_command_queue(4).expect("a queue"); + let mut buffers = Buffers::new(&device, 1 << 16); + for grid in [25, 1024] { + let want: Vec = (0..grid).map(|t| (t + 1) % grid + 1).collect(); + let out = buffers.buffer(4 * 1024); + write(&out, 0, &le_bytes(&[0xEEEE_EEEE; 1024])); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut encoder = command_buffer + .compute_command_encoder(DispatchType::Serial) + .expect("an encoder"); + encoder.set_compute_pipeline_state(&state).expect("a state"); + (encoder.set_threadgroup_memory_length(length, 0)).expect("a length"); + encoder.set_buffer(Some(&out), 0, 0).expect("a buffer"); + (encoder.dispatch_threads([grid, 1, 1], [1024, 1, 1])).unwrap_or_else(|error| { + panic!("{name}: a length of {length} past the answer {answer}: {error}") + }); + encoder.end_encoding(); + command_buffer.commit().expect("a commit"); + finished(name, &command_buffer); + assert_eq!(command_buffer.error(), None, "{name}"); + let got = words(&out, 0, grid as usize); + let first = got.iter().zip(&want).position(|(got, want)| got != want); + assert_eq!( + first, None, + "{name}: grid {grid}: the first word that differs" + ); + } + println!( + "{name}: a length of {length} of {limit} bytes, past the answer {answer}, ran \ + [25, 1, 1] and [1024, 1, 1] in [1024, 1, 1] and answered every word" + ); + }); + } + /// A kernel that reads, through the argument buffer at buffer 0 (one `texture2d` /// member, its 8-byte resource ID), the texture's width, height and texel `(0, 0)`'s red bits /// into words 0 to 2 of `out` (buffer 1). diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index e7fe0b1c7..f6b4b4c1e 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -5980,6 +5980,7 @@ method metal2vulkan-runtime::Device::import_dma_buf #[cfg(unix)] pub fn import_d method metal2vulkan-runtime::Device::import_dma_bufs #[cfg(unix)] pub fn import_dma_bufs(&self, chunks: Vec<(std::os::fd::OwnedFd, u64)>, release: Option>) -> Result<(Block, u32), Error> method metal2vulkan-runtime::Device::import_host_memory pub unsafe fn import_host_memory(&self, pointer: NonNull, len: u64, release: Option>) -> Result<(Block, u32), Error> method metal2vulkan-runtime::Device::loss pub fn loss(&self) -> Option +method metal2vulkan-runtime::Device::max_threadgroup_memory_length pub fn max_threadgroup_memory_length(&self) -> u32 method metal2vulkan-runtime::Device::memory_types pub fn memory_types(&self) -> floor::MemoryTypes method metal2vulkan-runtime::Device::minimum_linear_texture_alignment pub fn minimum_linear_texture_alignment(&self, pixel_format: PixelFormat) -> Result method metal2vulkan-runtime::Device::minimum_texture_buffer_alignment pub fn minimum_texture_buffer_alignment(&self, pixel_format: PixelFormat) -> Result diff --git a/docs/METAL-COVERAGE.md b/docs/METAL-COVERAGE.md index a075e8fea..5b66bb82c 100644 --- a/docs/METAL-COVERAGE.md +++ b/docs/METAL-COVERAGE.md @@ -10,12 +10,12 @@ Every public item of the macOS 27.2 SDK (Xcode 27.2, 27B52)'s Metal headers, by | Status | Items | Of which deprecated | |---|---|---| -| implemented | 637 | 29 | -| missing | 1074 | 34 | +| implemented | 638 | 29 | +| missing | 1073 | 34 | | out of scope | 424 | 5 | | all | 2135 | 68 | -Implemented by the runtime: 280; by the translator's values: 357. Missing by size: S 182, M 203, L 313, XL 376. +Implemented by the runtime: 281; by the translator's values: 357. Missing by size: S 181, M 203, L 313, XL 376. ## Missing, in build order @@ -28,7 +28,7 @@ Cheap items a plain app calls first, then medium pieces by how often a plain app | command queue descriptor | S | 3 | `MTLCommandQueueDescriptor`, `MTLCommandQueueDescriptor.maxCommandBufferCount`, `MTLDevice.newCommandQueueWithDescriptor:` | | compute, blit and resource-state pass descriptors | S | 10 | `MTLBlitPassDescriptor`, `MTLBlitPassDescriptor.blitPassDescriptor`, `MTLCommandBuffer.computeCommandEncoderWithDescriptor:`, ... | | libraries from a file path or URL | S | 2 | `MTLDevice.newLibraryWithFile:error:`, `MTLDevice.newLibraryWithURL:error:` | -| device, state and resource queries | S | 71 | `MTLAllocation.allocatedSize`, `MTLBuffer.sparseBufferTier`, `MTLCommandBuffer.device`, ... | +| device, state and resource queries | S | 70 | `MTLAllocation.allocatedSize`, `MTLBuffer.sparseBufferTier`, `MTLCommandBuffer.device`, ... | | plain-value constructors (`MTLOriginMake` and the rest) | S | 7 | `MTLOriginMake`, `MTLSizeMake`, `MTLRegionMake1D`, ... | | a buffer made with bytes | S | 1 | `MTLDevice.newBufferWithBytes:length:options:` | | pipeline creation forms (from a function, with a completion handler) | S | 6 | `MTLDevice.newRenderPipelineStateWithDescriptor:options:completionHandler:`, `MTLDevice.newComputePipelineStateWithFunction:error:`, `MTLDevice.newComputePipelineStateWithFunction:options:reflection:error:`, ... | @@ -1452,7 +1452,7 @@ Cheap items a plain app calls first, then medium pieces by how often a plain app | `MTLDevice.newRenderPipelineStateWithTileDescriptor:options:completionHandler:` | method | missing | L: tile render pipelines; metal2vulkan-runtime makes none | | `MTLDevice.newRenderPipelineStateWithMeshDescriptor:options:reflection:error:` | method | missing | L: mesh render pipelines; metal2vulkan-runtime makes none | | `MTLDevice.newRenderPipelineStateWithMeshDescriptor:options:completionHandler:` | method | missing | L: mesh render pipelines; metal2vulkan-runtime makes none | -| `MTLDevice.maxThreadgroupMemoryLength` | property | missing | S: a query or call metal2vulkan-runtime does not answer | +| `MTLDevice.maxThreadgroupMemoryLength` | property | implemented | `Device::max_threadgroup_memory_length` (runtime) | | `MTLDevice.maxArgumentBufferSamplerCount` | property | missing | S: a query or call metal2vulkan-runtime does not answer | | `MTLDevice.programmableSamplePositionsSupported` | property | missing | S: a query or call metal2vulkan-runtime does not answer | | `MTLDevice.getDefaultSamplePositions:count:` | method | missing | S: the standard positions a pass without `sample_positions` rasterizes at | diff --git a/scripts/metal-coverage/coverage.tsv b/scripts/metal-coverage/coverage.tsv index e881746c1..09a43a2de 100644 --- a/scripts/metal-coverage/coverage.tsv +++ b/scripts/metal-coverage/coverage.tsv @@ -1116,7 +1116,7 @@ MTLDevice.h MTLDevice method newRenderPipelineStateWithTileDescriptor:options:re MTLDevice.h MTLDevice method newRenderPipelineStateWithTileDescriptor:options:completionHandler: M tile render pipelines; metal2vulkan-runtime makes none L tile MTLDevice.h MTLDevice method newRenderPipelineStateWithMeshDescriptor:options:reflection:error: M mesh render pipelines; metal2vulkan-runtime makes none L mesh MTLDevice.h MTLDevice method newRenderPipelineStateWithMeshDescriptor:options:completionHandler: M mesh render pipelines; metal2vulkan-runtime makes none L mesh -MTLDevice.h MTLDevice property maxThreadgroupMemoryLength M a query or call metal2vulkan-runtime does not answer S queries +MTLDevice.h MTLDevice property maxThreadgroupMemoryLength I runtime Device::max_threadgroup_memory_length MTLDevice.h MTLDevice property maxArgumentBufferSamplerCount M a query or call metal2vulkan-runtime does not answer S queries MTLDevice.h MTLDevice property programmableSamplePositionsSupported M a query or call metal2vulkan-runtime does not answer S queries MTLDevice.h MTLDevice method getDefaultSamplePositions:count: M the standard positions a pass without `sample_positions` rasterizes at S queries