diff --git a/CHANGELOG.md b/CHANGELOG.md index 49e9bcb..ada8094 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game remains unsupported. ### Changed +- Added non-blocking Metal compute submission through `submit_words` and `wait`, with completion-aware resource retirement and a sixteen-dispatch in-flight limit. Synchronous calls keep their existing behavior. The benchmark reports the host submission split and compares synchronous and pipelined batches. - Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits. ### Added diff --git a/benchmarks/src/main.rs b/benchmarks/src/main.rs index 0d068a5..490ae6d 100644 --- a/benchmarks/src/main.rs +++ b/benchmarks/src/main.rs @@ -14,11 +14,12 @@ use std::path::PathBuf; use std::process::Command; use std::time::{SystemTime, UNIX_EPOCH}; -use xenora_metal::NativeCompute; +use xenora_metal::{NativeCompute, RunProfile}; use xenora_shader::{Architecture, ENTRY_POINT, compile}; const WARMUP_REPS: usize = 2; const DEFAULT_REPS: usize = 7; +const BATCH: usize = 8; #[derive(Debug, Clone)] struct Fixture { @@ -83,10 +84,66 @@ struct SizeResult { pipeline: Stats, gpu: Stats, host: Stats, + /// Host submission stages inside `host`, plus readback after it. + submit: SubmitStats, /// Fraction of samples whose GPU timestamp delta was zero. gpu_zero_fraction: f64, } +/// Host-side split of one dispatch's submission path. +/// +/// `other` is `host` minus library, pipeline and the four stages below it, +/// per sample: compile options, function lookup, bounds and validation checks. +#[derive(Debug, Clone, Default)] +struct SubmitStats { + alloc: Stats, + encode: Stats, + commit: Stats, + wait: Stats, + readback: Stats, + other: Stats, +} + +#[derive(Debug, Clone, Default)] +struct SubmitSamples { + alloc: Vec, + encode: Vec, + commit: Vec, + wait: Vec, + readback: Vec, + other: Vec, +} + +impl SubmitSamples { + fn push(&mut self, profile: &RunProfile) { + self.alloc.push(profile.alloc_seconds); + self.encode.push(profile.encode_seconds); + self.commit.push(profile.commit_seconds); + self.wait.push(profile.wait_seconds); + self.readback.push(profile.readback_seconds); + self.other.push( + profile.host_seconds + - profile.library_seconds + - profile.pipeline_seconds + - profile.alloc_seconds + - profile.encode_seconds + - profile.commit_seconds + - profile.wait_seconds, + ); + } + + fn stats(self) -> SubmitStats { + SubmitStats { + alloc: Stats::from_samples(self.alloc), + encode: Stats::from_samples(self.encode), + commit: Stats::from_samples(self.commit), + wait: Stats::from_samples(self.wait), + readback: Stats::from_samples(self.readback), + other: Stats::from_samples(self.other), + } + } +} + #[derive(Debug, Clone)] struct FixtureResult { name: String, @@ -95,6 +152,14 @@ struct FixtureResult { status: String, reason: String, sizes: Vec, + batch: Option, +} + +#[derive(Debug, Clone)] +struct BatchResult { + words: usize, + sync: Stats, + pipelined: Stats, } fn main() -> Result<(), Box> { @@ -180,6 +245,7 @@ fn run_fixture(metal: &NativeCompute, fixture: &Fixture, reps: usize) -> Fixture status: "not-implemented".to_string(), reason: String::new(), sizes: Vec::new(), + batch: None, }; let code = match fs::read(&fixture.path) { @@ -242,6 +308,7 @@ fn run_fixture(metal: &NativeCompute, fixture: &Fixture, reps: usize) -> Fixture let mut pipeline_samples = Vec::with_capacity(reps); let mut gpu_samples = Vec::with_capacity(reps); let mut host_samples = Vec::with_capacity(reps); + let mut submit_samples = SubmitSamples::default(); let mut gpu_zero = 0usize; let mut mismatch = None; @@ -275,6 +342,7 @@ fn run_fixture(metal: &NativeCompute, fixture: &Fixture, reps: usize) -> Fixture pipeline_samples.push(profile.pipeline_seconds); gpu_samples.push(profile.gpu_seconds); host_samples.push(profile.host_seconds); + submit_samples.push(&profile); if profile.gpu_seconds <= 0.0 { gpu_zero += 1; } @@ -294,6 +362,7 @@ fn run_fixture(metal: &NativeCompute, fixture: &Fixture, reps: usize) -> Fixture pipeline: Stats::from_samples(pipeline_samples), gpu: Stats::from_samples(gpu_samples), host: Stats::from_samples(host_samples), + submit: submit_samples.stats(), gpu_zero_fraction: if measured == 0 { 0.0 } else { @@ -302,11 +371,83 @@ fn run_fixture(metal: &NativeCompute, fixture: &Fixture, reps: usize) -> Fixture }); } + let batch_words = fixture + .sizes + .iter() + .copied() + .min_by_key(|words| words.abs_diff(1024)) + .unwrap_or(1024); + match measure_batch(metal, &code, fixture, batch_words, reps) { + Ok(batch) => result.batch = Some(batch), + Err(reason) => { + result.status = "excluded".to_string(); + result.reason = reason; + return result; + } + } result.sizes = sizes; result.status = "benchmarked".to_string(); result } +fn measure_batch( + metal: &NativeCompute, + code: &[u8], + fixture: &Fixture, + words: usize, + reps: usize, +) -> Result { + let input = expand(&fixture.input, words); + let expected = expand(&fixture.expected, words); + let mut sync = Vec::with_capacity(reps); + let mut pipelined = Vec::with_capacity(reps); + for rep in 0..(WARMUP_REPS + reps) { + for (samples, variant) in [(&mut sync, "sync"), (&mut pipelined, "pipelined")] { + let mut tokens = Vec::with_capacity(BATCH); + let mut outputs = Vec::with_capacity(BATCH); + let start = std::time::Instant::now(); + for _ in 0..BATCH { + let compiled = compile(Architecture::Gfx1030, code).map_err(|error| { + format!("{variant} batch compile failed at {words} words: {error}") + })?; + if variant == "sync" { + let profile = metal + .run_words_profiled(&compiled.msl, ENTRY_POINT, &input) + .map_err(|error| { + format!("{variant} batch run failed at {words} words: {error}") + })?; + outputs.push(profile.output); + } else { + let token = metal + .submit_words(&compiled.msl, ENTRY_POINT, &input) + .map_err(|error| { + format!("{variant} batch submit failed at {words} words: {error}") + })?; + tokens.push(token); + } + } + for token in tokens { + let profile = metal.wait(token).map_err(|error| { + format!("{variant} batch wait failed at {words} words: {error}") + })?; + outputs.push(profile.output); + } + let per_dispatch = start.elapsed().as_secs_f64() / BATCH as f64; + if outputs.iter().any(|output| *output != expected) { + return Err(format!("{variant} batch GPU mismatch at {words} words")); + } + if rep >= WARMUP_REPS { + samples.push(per_dispatch); + } + } + } + Ok(BatchResult { + words, + sync: Stats::from_samples(sync), + pipelined: Stats::from_samples(pipelined), + }) +} + fn expand(base: &[u32], words: usize) -> Vec { (0..words).map(|i| base[i % base.len()]).collect() } @@ -612,13 +753,19 @@ fn results_json(results: &[FixtureResult]) -> String { for (size_index, size) in result.sizes.iter().enumerate() { let _ = writeln!( out, - " {{ \"words\": {}, \"compile\": {}, \"library\": {}, \"pipeline\": {}, \"gpu\": {}, \"host\": {}, \"gpu_zero_fraction\": {:.4} }}{}", + " {{ \"words\": {}, \"compile\": {}, \"library\": {}, \"pipeline\": {}, \"gpu\": {}, \"host\": {}, \"alloc\": {}, \"encode\": {}, \"commit\": {}, \"wait\": {}, \"readback\": {}, \"host_other\": {}, \"gpu_zero_fraction\": {:.4} }}{}", size.words, stats_json(&size.compile), stats_json(&size.library), stats_json(&size.pipeline), stats_json(&size.gpu), stats_json(&size.host), + stats_json(&size.submit.alloc), + stats_json(&size.submit.encode), + stats_json(&size.submit.commit), + stats_json(&size.submit.wait), + stats_json(&size.submit.readback), + stats_json(&size.submit.other), size.gpu_zero_fraction, if size_index + 1 == result.sizes.len() { "" @@ -627,9 +774,19 @@ fn results_json(results: &[FixtureResult]) -> String { } ); } + out.push_str(" ]"); + if let Some(batch) = &result.batch { + let _ = write!( + out, + ",\n \"batch\": {{ \"dispatches\": {BATCH}, \"words\": {}, \"sync\": {}, \"pipelined\": {} }}", + batch.words, + stats_json(&batch.sync), + stats_json(&batch.pipelined) + ); + } let _ = writeln!( out, - " ]\n }}{}", + "\n }}{}", if index + 1 == results.len() { "" } else { "," } ); } @@ -644,7 +801,7 @@ fn report_markdown(metadata: &Metadata, results: &[FixtureResult]) -> String { let _ = writeln!( out, "Generated by `xenora-bench`. Every timed fixture passed its correctness test in this run. \ - Timings are single command-buffer samples; see `docs/testing/benchmarks.md` for the protocol." + See `docs/testing/benchmarks.md` for the single-dispatch protocol." ); let _ = writeln!(out); let _ = writeln!(out, "## Environment"); @@ -739,5 +896,70 @@ fn report_markdown(metadata: &Metadata, results: &[FixtureResult]) -> String { ); } } + + let _ = writeln!(out); + let _ = writeln!(out, "## Submission split"); + let _ = writeln!(out); + let _ = writeln!( + out, + "Medians in microseconds of the host stages inside `host`: `alloc` creates the input and \ + output shared buffers, `encode` creates the command buffer and encodes the dispatch, \ + `commit` and `wait` time `commit` and `waitUntilCompleted`, and `other` is the per-sample \ + remainder of `host` after library, pipeline and these four stages. `readback` copies \ + the output after `host` ends." + ); + let _ = writeln!(out); + let _ = writeln!( + out, + "| Fixture | Words | host | alloc | encode | commit | wait | other | readback |" + ); + let _ = writeln!( + out, + "| --- | --- | --- | --- | --- | --- | --- | --- | --- |" + ); + for result in results.iter().filter(|r| r.status == "benchmarked") { + for size in &result.sizes { + let stages = &size.submit; + let _ = writeln!( + out, + "| {} | {} | {:.2} | {:.2} | {:.2} | {:.2} | {:.2} | {:.2} | {:.2} |", + result.name, + size.words, + size.host.median * 1e6, + stages.alloc.median * 1e6, + stages.encode.median * 1e6, + stages.commit.median * 1e6, + stages.wait.median * 1e6, + stages.other.median * 1e6, + stages.readback.median * 1e6 + ); + } + } + let _ = writeln!(out); + let _ = writeln!(out, "## Batched submission"); + let _ = writeln!(out); + let _ = writeln!( + out, + "Median host microseconds per dispatch in batches of {BATCH}, including recompilation." + ); + let _ = writeln!(out); + let _ = writeln!( + out, + "| Fixture | Words | Sync (µs) | Pipelined (µs) | Sync / pipelined |" + ); + let _ = writeln!(out, "| --- | --- | --- | --- | --- |"); + for result in results { + if let Some(batch) = &result.batch { + let _ = writeln!( + out, + "| {} | {} | {:.2} | {:.2} | {:.2}× |", + result.name, + batch.words, + batch.sync.median * 1e6, + batch.pipelined.median * 1e6, + batch.sync.median / batch.pipelined.median + ); + } + } out } diff --git a/crates/metal/Cargo.toml b/crates/metal/Cargo.toml index 9f5789f..556efa5 100644 --- a/crates/metal/Cargo.toml +++ b/crates/metal/Cargo.toml @@ -41,6 +41,7 @@ objc2-metal = { version = "=0.3.2", default-features = false, features = [ "MTLComputePipeline", "MTLDepthStencil", "MTLDevice", + "MTLEvent", "MTLLibrary", "MTLPixelFormat", "MTLPipeline", diff --git a/crates/metal/src/compute.rs b/crates/metal/src/compute.rs index f66c403..ebed2ad 100644 --- a/crates/metal/src/compute.rs +++ b/crates/metal/src/compute.rs @@ -1,9 +1,12 @@ +use std::collections::BTreeMap; use std::ffi::c_void; use std::fmt; use std::mem::size_of_val; use std::ptr::{NonNull, copy_nonoverlapping}; +use std::sync::{Mutex, MutexGuard, PoisonError}; use std::time::Instant; +use objc2::Message; use objc2::rc::{Retained, autoreleasepool}; use objc2::runtime::{NSObjectProtocol, ProtocolObject}; use objc2::sel; @@ -13,8 +16,8 @@ use objc2_metal::{ MTLCompileOptions, MTLComputeCommandEncoder, MTLComputePipelineState, MTLCreateSystemDefaultDevice, MTLDevice, MTLFunction, MTLGPUFamily, MTLLibrary, MTLMathFloatingPointFunctions, MTLMathMode, MTLOrigin, MTLPixelFormat, MTLRegion, - MTLResourceOptions, MTLShaderValidation, MTLSize, MTLStorageMode, MTLTexture, - MTLTextureDescriptor, MTLTextureUsage, + MTLResourceOptions, MTLSamplerState, MTLShaderValidation, MTLSharedEvent, MTLSize, + MTLStorageMode, MTLTexture, MTLTextureDescriptor, MTLTextureUsage, }; use xenora_texture::{ Bc1Upload, BcAlphaFormat, BcAlphaUpload, BcChannelFormat, BcChannelUpload, TiledBc1, @@ -33,6 +36,7 @@ const MAX_THREADS_PER_GROUP: usize = 64; const MAX_GROUPS: usize = 64; const MAX_GRID_WORDS: usize = MAX_GROUPS * MAX_THREADS_PER_GROUP; const MAX_SOURCE_BYTES: usize = 64 * 1024; +const MAX_IN_FLIGHT: usize = 16; const BC_READBACK: &str = r" #include @@ -65,7 +69,7 @@ enum ComputeInput<'a> { Texture(&'a ProtocolObject, usize), SampledTexture { texture: &'a ProtocolObject, - sampler: &'a ProtocolObject, + sampler: &'a ProtocolObject, coords: &'a [u32], }, } @@ -147,7 +151,18 @@ pub struct RunProfile { pub library_seconds: f64, pub pipeline_seconds: f64, pub gpu_seconds: f64, + /// Host wall time from the start of setup until wait observes completion. pub host_seconds: f64, + /// Host time to allocate the input and output shared buffers. + pub alloc_seconds: f64, + /// Host time to create the command buffer and encode the dispatch. + pub encode_seconds: f64, + /// Host time spent in `commit`. + pub commit_seconds: f64, + /// Host time spent in `waitUntilCompleted`. + pub wait_seconds: f64, + /// Host time to copy the output words back; not part of `host_seconds`. + pub readback_seconds: f64, pub output: Vec, } @@ -155,10 +170,161 @@ pub struct RunProfile { pub struct NativeCompute { device: Retained>, queue: Retained>, + submissions: Mutex, +} + +/// A submitted dispatch whose result can be collected by its issuing context. +#[must_use] +pub struct Submission<'a> { + context: &'a NativeCompute, + id: u64, +} + +impl Drop for Submission<'_> { + fn drop(&mut self) { + let mut table = self.context.submissions(); + if let Some(entry) = table.entries.get_mut(&self.id) { + if entry.resources.is_some() { + entry.abandoned = true; + } else { + table.entries.remove(&self.id); + } + } + } +} + +#[doc(hidden)] +pub struct SubmissionGate { + event: Retained>, +} + +impl SubmissionGate { + pub fn open(&self) { + self.event.setSignaledValue(1); + } +} + +impl Drop for SubmissionGate { + fn drop(&mut self) { + self.open(); + } +} + +#[derive(Default)] +struct SubmissionTable { + next_id: u64, + entries: BTreeMap, +} + +impl SubmissionTable { + fn in_flight(&self) -> usize { + self.entries + .values() + .filter(|entry| entry.resources.is_some()) + .count() + } + + fn check_capacity(&self) -> Result<(), MetalError> { + if self.in_flight() >= MAX_IN_FLIGHT { + return Err(MetalError::new( + "in-flight limit", + format!("at most {MAX_IN_FLIGHT} compute submissions may be in flight"), + )); + } + Ok(()) + } +} + +struct SubmissionEntry { + resources: Option, + result: Result, + host_start: Instant, + abandoned: bool, + waiting: bool, +} + +/// Owns every resource referenced by the unretained command buffer until +/// Metal reports Completed or Error. +struct InFlightResources { + command: Retained>, + _pipeline: Retained>, + _input: Option>>, + output: Retained>, + _texture: Option>>, + _sampler: Option>>, + gate: Option>>, + word_count: usize, +} + +// SAFETY: Metal permits command buffers to move between threads with exclusive +// access. The table mutex and waiting flag keep sweeps off a command during its +// wait. Readback uses private shared storage after GPU completion. Retained +// textures and input buffers are only kept alive by the table. +unsafe impl Send for InFlightResources {} + +impl SubmissionEntry { + fn retire(&mut self, status: MTLCommandBufferStatus) { + if !is_terminal(status) { + return; + } + let Some(resources) = self.resources.take() else { + return; + }; + if let Err(error) = check_command_status(&resources.command, status) { + self.result = Err(error); + return; + } + if let Ok(profile) = &mut self.result { + profile.gpu_seconds = resources.command.GPUEndTime() - resources.command.GPUStartTime(); + profile.host_seconds = self.host_start.elapsed().as_secs_f64(); + let readback_start = Instant::now(); + let byte_len = resources.word_count * size_of::(); + // SAFETY: The initialized shared output is distinct from the host + // vector and the GPU has finished writing to it. Both ranges hold + // byte_len bytes and all u32 bit patterns are valid. + unsafe { + copy_nonoverlapping( + resources.output.contents().cast::().as_ptr(), + profile.output.as_mut_ptr().cast::(), + byte_len, + ); + } + profile.readback_seconds = readback_start.elapsed().as_secs_f64(); + } + } +} + +impl Drop for NativeCompute { + fn drop(&mut self) { + // Tokens can be abandoned (or forgotten) while their work is pending. + // Open all remaining gates before draining the queue. + let table = self + .submissions + .get_mut() + .unwrap_or_else(PoisonError::into_inner); + for resources in table + .entries + .values() + .filter_map(|entry| entry.resources.as_ref()) + { + if let Some(gate) = &resources.gate { + gate.setSignaledValue(1); + } + } + for (_, entry) in std::mem::take(&mut table.entries) { + if let Some(resources) = entry.resources { + resources.command.waitUntilCompleted(); + if !is_terminal(resources.command.status()) { + // Preserve the resources if Metal unexpectedly returns before completion. + std::mem::forget(resources); + } + } + } + } } impl NativeCompute { - /// Open the default Apple GPU and create a retained-resource command queue. + /// Open the default Apple GPU and create a command queue. /// /// # Errors /// @@ -178,10 +344,47 @@ impl NativeCompute { let queue = device .newCommandQueue() .ok_or_else(|| MetalError::new("newCommandQueue", "queue creation failed"))?; - Ok(Self { device, queue }) + Ok(Self { + device, + queue, + submissions: Mutex::default(), + }) }) } + fn submissions(&self) -> MutexGuard<'_, SubmissionTable> { + self.submissions + .lock() + .unwrap_or_else(PoisonError::into_inner) + } + + fn retire_completed(&self) { + self.submissions().entries.retain(|_, entry| { + if !entry.waiting + && let Some(resources) = &entry.resources + { + entry.retire(resources.command.status()); + } + !entry.abandoned || entry.resources.is_some() + }); + } + + fn begin_submission(&self) -> Instant { + let host_start = Instant::now(); + self.retire_completed(); + host_start + } + + #[doc(hidden)] + pub fn in_flight(&self) -> usize { + self.submissions().in_flight() + } + + #[doc(hidden)] + pub fn tracked(&self) -> usize { + self.submissions().entries.len() + } + /// Report the selected device's registered name. pub fn device_name(&self) -> String { autoreleasepool(|_| self.device.name().to_string()) @@ -561,6 +764,122 @@ kernel void sample_rgba8(texture2d tex [[texture(0)]], self.run_profiled_words(source, entry, input, None) } + /// Submit trusted MSL with read-only words at buffer 0 and output words at buffer 1. + /// + /// The trusted-kernel requirements of [`Self::run_words`] apply. + /// Use [`Self::wait`] to collect the result. + /// + /// # Errors + /// + /// Returns an error for invalid input or source, compilation or dispatch + /// setup failure, or a full in-flight table. + pub fn submit_words( + &self, + source: &str, + entry: &str, + input: &[u32], + ) -> Result, MetalError> { + autoreleasepool(|_| { + let host_start = self.begin_submission(); + validate_words(source, entry, input)?; + self.submit_sized( + source, + entry, + ComputeInput::Words(input), + None, + None, + host_start, + ) + }) + } + + #[doc(hidden)] + pub fn submit_words_gated( + &self, + source: &str, + entry: &str, + input: &[u32], + ) -> Result<(Submission<'_>, SubmissionGate), MetalError> { + autoreleasepool(|_| { + let host_start = self.begin_submission(); + validate_words(source, entry, input)?; + let event = self + .device + .newSharedEvent() + .ok_or_else(|| MetalError::new("newSharedEvent", "gate creation failed"))?; + let submission = self.submit_sized( + source, + entry, + ComputeInput::Words(input), + None, + Some(&event), + host_start, + )?; + Ok((submission, SubmissionGate { event })) + }) + } + + /// Wait for this context's submission and return its readback and timings. + /// + /// # Errors + /// + /// Returns an error for a token from another context, an unknown submission, + /// or a Metal completion failure. + pub fn wait(&self, submission: Submission<'_>) -> Result { + if !std::ptr::eq(self, submission.context) { + return Err(MetalError::new( + "submission", + "token belongs to another context", + )); + } + autoreleasepool(|_| { + let id = submission.id; + std::mem::forget(submission); + let result = self.take_result(id); + self.retire_completed(); + result + }) + } + + fn take_result(&self, id: u64) -> Result { + let unknown = || MetalError::new("submission", "unknown submission id"); + let command = { + let mut table = self.submissions(); + let entry = table.entries.get_mut(&id).ok_or_else(unknown)?; + entry.resources.as_ref().map(|resources| { + entry.waiting = true; + resources.command.clone() + }) + }; + let wait_seconds = command.map_or(0.0, |command| { + // Keep the table available to other submitters while Metal waits. + let start = Instant::now(); + command.waitUntilCompleted(); + start.elapsed().as_secs_f64() + }); + + let mut table = self.submissions(); + let entry = table.entries.get_mut(&id).ok_or_else(unknown)?; + entry.waiting = false; + let host_seconds = if let Some(resources) = &entry.resources { + let status = resources.command.status(); + if !is_terminal(status) { + entry.abandoned = true; + check_command_status(&resources.command, status)?; + } + entry.retire(status); + None + } else { + Some(entry.host_start.elapsed().as_secs_f64()) + }; + let mut profile = table.entries.remove(&id).ok_or_else(unknown)?.result?; + profile.wait_seconds = wait_seconds; + if let Some(host_seconds) = host_seconds { + profile.host_seconds = host_seconds; + } + Ok(profile) + } + /// Run trusted MSL with an explicit one-dimensional threadgroup width. /// /// The grid still contains one invocation per input word. The requested width @@ -608,13 +927,7 @@ kernel void sample_rgba8(texture2d tex [[texture(0)]], input: &[u32], group_width: Option, ) -> Result { - if !(1..=MAX_GRID_WORDS).contains(&input.len()) { - return Err(MetalError::new( - "dispatch bounds", - format!("expected 1..={MAX_GRID_WORDS} words, got {}", input.len()), - )); - } - validate_source(source, &[entry])?; + validate_words(source, entry, input)?; autoreleasepool(|_| self.run_sized(source, entry, ComputeInput::Words(input), group_width)) } @@ -636,7 +949,20 @@ kernel void sample_rgba8(texture2d tex [[texture(0)]], input: ComputeInput<'_>, group_width: Option, ) -> Result { - let host_start = Instant::now(); + let host_start = self.begin_submission(); + self.wait(self.submit_sized(source, entry, input, group_width, None, host_start)?) + } + + fn submit_sized( + &self, + source: &str, + entry: &str, + input: ComputeInput<'_>, + group_width: Option, + gate: Option<&ProtocolObject>, + host_start: Instant, + ) -> Result, MetalError> { + self.submissions().check_capacity()?; let options = compile_options()?; let library_start = Instant::now(); let library = self.compile_library(source, &options)?; @@ -672,17 +998,29 @@ kernel void sample_rgba8(texture2d tex [[texture(0)]], "fixture exceeds device buffer limit", )); } + let alloc_start = Instant::now(); let input_buffer = match input { ComputeInput::Words(words) => Some(self.new_buffer(words)?), ComputeInput::SampledTexture { coords, .. } => Some(self.new_buffer(coords)?), ComputeInput::Texture(..) => None, }; - let mut words = vec![0xA5A5_A5A5; input.len()]; + let words = vec![0xA5A5_A5A5; input.len()]; let output_buffer = self.new_buffer(&words)?; + let alloc_seconds = alloc_start.elapsed().as_secs_f64(); + let mut table = self.submissions(); + table.check_capacity()?; + let id = table.next_id; + table.next_id = id + .checked_add(1) + .ok_or_else(|| MetalError::new("submission", "submission ids exhausted"))?; + let encode_start = Instant::now(); let command = self .queue - .commandBuffer() + .commandBufferWithUnretainedReferences() .ok_or_else(|| MetalError::new("commandBuffer", "command buffer creation failed"))?; + if let Some(gate) = gate { + command.encodeWaitForEvent_value(gate.as_ref(), 1); + } let encoder = command.computeCommandEncoder().ok_or_else(|| { MetalError::new("computeCommandEncoder", "compute encoder creation failed") })?; @@ -710,27 +1048,49 @@ kernel void sample_rgba8(texture2d tex [[texture(0)]], } encoder.dispatchThreads_threadsPerThreadgroup(size(input.len()), size(width)); encoder.endEncoding(); - complete_command(&command)?; - let gpu_seconds = command.GPUEndTime() - command.GPUStartTime(); - let host_seconds = host_start.elapsed().as_secs_f64(); - // SAFETY: Metal copied the initialized words into distinct shared storage. - // The GPU finished before the CPU touches that storage. Both ranges are - // valid for byte_len bytes and don't overlap. A byte copy requires no - // additional alignment and all u32 bit patterns are valid. - unsafe { - copy_nonoverlapping( - output_buffer.contents().cast::().as_ptr(), - words.as_mut_ptr().cast::(), - byte_len, - ); - } - Ok(RunProfile { - library_seconds, - pipeline_seconds, - gpu_seconds, - host_seconds, - output: words, - }) + let encode_seconds = encode_start.elapsed().as_secs_f64(); + let (texture, sampler) = match input { + ComputeInput::Texture(texture, _) => (Some(texture.retain()), None), + ComputeInput::SampledTexture { + texture, sampler, .. + } => (Some(texture.retain()), Some(sampler.retain())), + ComputeInput::Words(_) => (None, None), + }; + let resources = InFlightResources { + command, + _pipeline: pipeline, + _input: input_buffer, + output: output_buffer, + _texture: texture, + _sampler: sampler, + gate: gate.map(Message::retain), + word_count: input.len(), + }; + let commit_start = Instant::now(); + resources.command.commit(); + let commit_seconds = commit_start.elapsed().as_secs_f64(); + table.entries.insert( + id, + SubmissionEntry { + resources: Some(resources), + result: Ok(RunProfile { + library_seconds, + pipeline_seconds, + gpu_seconds: 0.0, + host_seconds: 0.0, + alloc_seconds, + encode_seconds, + commit_seconds, + wait_seconds: 0.0, + readback_seconds: 0.0, + output: words, + }), + host_start, + abandoned: false, + waiting: false, + }, + ); + Ok(Submission { context: self, id }) } fn compile_library( @@ -790,6 +1150,16 @@ kernel void sample_rgba8(texture2d tex [[texture(0)]], } } +fn validate_words(source: &str, entry: &str, input: &[u32]) -> Result<(), MetalError> { + if !(1..=MAX_GRID_WORDS).contains(&input.len()) { + return Err(MetalError::new( + "dispatch bounds", + format!("expected 1..={MAX_GRID_WORDS} words, got {}", input.len()), + )); + } + validate_source(source, &[entry]) +} + fn validate_source(source: &str, entries: &[&str]) -> Result<(), MetalError> { if source.is_empty() || source.len() > MAX_SOURCE_BYTES @@ -829,11 +1199,29 @@ fn find_function( fn complete_command(command: &ProtocolObject) -> Result<(), MetalError> { command.commit(); - command.waitUntilCompleted(); + wait_command(command) +} - if command.status() != MTLCommandBufferStatus::Completed { +/// Block until a committed command buffer finishes and check its status. +fn wait_command(command: &ProtocolObject) -> Result<(), MetalError> { + command.waitUntilCompleted(); + check_command_status(command, command.status()) +} + +fn is_terminal(status: MTLCommandBufferStatus) -> bool { + matches!( + status, + MTLCommandBufferStatus::Completed | MTLCommandBufferStatus::Error + ) +} + +fn check_command_status( + command: &ProtocolObject, + status: MTLCommandBufferStatus, +) -> Result<(), MetalError> { + if status != MTLCommandBufferStatus::Completed { let error = command.error().map_or_else( - || format!("unexpected command status {:?}", command.status()), + || format!("unexpected command status {status:?}"), |error| error.localizedDescription().to_string(), ); return Err(MetalError::new("waitUntilCompleted", error)); diff --git a/crates/metal/src/lib.rs b/crates/metal/src/lib.rs index a8c56d1..22ff47c 100644 --- a/crates/metal/src/lib.rs +++ b/crates/metal/src/lib.rs @@ -16,7 +16,8 @@ pub mod texture_pipeline; pub use compute::{ BlendDraw, BlendFactor, BlendOperation, BlendPass, BlendState, ColorWriteMask, DepthCompare, DepthDraw, DepthFill, DepthOutput, DepthPass, DepthState, GuestBuffer, GuestBufferView, - IndexBuffer, IndexedDraw, IndexedPass, MetalError, NativeCompute, RunProfile, + IndexBuffer, IndexedDraw, IndexedPass, MetalError, NativeCompute, RunProfile, Submission, + SubmissionGate, }; #[cfg(all(target_arch = "aarch64", target_os = "macos"))] diff --git a/crates/metal/tests/native/submission.rs b/crates/metal/tests/native/submission.rs new file mode 100644 index 0000000..0afbdd5 --- /dev/null +++ b/crates/metal/tests/native/submission.rs @@ -0,0 +1,104 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +use super::{context, fixture, native}; + +const ENTRY: &str = "fixture"; +const INPUT: [u32; 4] = [0, 1, 71, u32::MAX]; +const LIMIT: usize = 16; + +fn source() -> String { + fixture("output[id] = input[id] * 3u + 7u;") +} + +fn expected(input: &[u32]) -> Vec { + input + .iter() + .map(|word| word.wrapping_mul(3).wrapping_add(7)) + .collect() +} + +#[test] +fn sweep_keeps_resources_until_completion() { + let metal = context(); + let source = source(); + let (a, gate) = native(metal.submit_words_gated(&source, ENTRY, &INPUT)); + assert_eq!(metal.in_flight(), 1); + let b = native(metal.submit_words(&source, ENTRY, &INPUT)); + assert_eq!(metal.in_flight(), 2); + gate.open(); + assert_eq!(native(metal.wait(a)).output, expected(&INPUT)); + assert_eq!(native(metal.wait(b)).output, expected(&INPUT)); + assert_eq!(metal.in_flight(), 0); +} + +#[test] +fn batch_can_be_collected_in_either_order() { + let metal = context(); + let source = source(); + for reverse in [false, true] { + let mut batch = Vec::new(); + for seed in 0..8 { + let input = INPUT.map(|word| word.wrapping_add(seed)); + batch.push((input, native(metal.submit_words(&source, ENTRY, &input)))); + } + if reverse { + batch.reverse(); + } + for (input, submission) in batch { + let output = native(metal.wait(submission)).output; + assert_eq!(output, expected(&input)); + assert_eq!(output, native(metal.run_words(&source, ENTRY, &input))); + } + assert_eq!(metal.tracked(), 0); + } +} + +#[test] +fn full_queue_returns_in_flight_limit_error() { + let metal = context(); + let source = source(); + let (first, gate) = native(metal.submit_words_gated(&source, ENTRY, &INPUT)); + let mut tokens = vec![first]; + for _ in 1..LIMIT { + tokens.push(native(metal.submit_words(&source, ENTRY, &INPUT))); + } + assert_eq!(metal.in_flight(), LIMIT); + let Err(error) = metal.submit_words(&source, ENTRY, &INPUT) else { + panic!("submission past the in-flight limit succeeded"); + }; + assert_eq!(error.operation, "in-flight limit"); + gate.open(); + for token in tokens { + assert_eq!(native(metal.wait(token)).output, expected(&INPUT)); + } + assert_eq!(metal.in_flight(), 0); +} + +#[test] +fn dropped_token_retires_after_completion() { + let metal = context(); + let source = source(); + let (a, gate) = native(metal.submit_words_gated(&source, ENTRY, &INPUT)); + drop(a); + let b = native(metal.submit_words(&source, ENTRY, &INPUT)); + assert_eq!(metal.in_flight(), 2); + drop(gate); + assert_eq!(native(metal.wait(b)).output, expected(&INPUT)); + assert_eq!(metal.in_flight(), 0); + assert_eq!(metal.tracked(), 0); +} + +#[test] +fn finished_result_survives_later_submission() { + let metal = context(); + let source = source(); + let a = native(metal.submit_words(&source, ENTRY, &INPUT)); + let b = native(metal.submit_words(&source, ENTRY, &[9])); + assert_eq!(native(metal.wait(b)).output, expected(&[9])); + assert_eq!(metal.in_flight(), 0); + assert_eq!(metal.tracked(), 1); + let profile = native(metal.wait(a)); + assert_eq!(profile.output, expected(&INPUT)); + assert_eq!(profile.wait_seconds, 0.0); + assert_eq!(metal.tracked(), 0); +} diff --git a/crates/metal/tests/native_compute.rs b/crates/metal/tests/native_compute.rs index 2e80250..933cb97 100644 --- a/crates/metal/tests/native_compute.rs +++ b/crates/metal/tests/native_compute.rs @@ -16,6 +16,8 @@ mod indexed; mod indexed_cases; #[path = "native/offscreen.rs"] mod offscreen; +#[path = "native/submission.rs"] +mod submission; #[path = "native/texture.rs"] mod texture; #[path = "native/texture_bc_alpha.rs"]