use objc2::rc::Retained;
use objc2::runtime::ProtocolObject;
use objc2_foundation::NSString;
use objc2_metal::*;
use std::collections::HashMap;
use std::ffi::c_void;
use std::ptr::NonNull;
pub type Buf = Retained<ProtocolObject<dyn MTLBuffer>>;
pub type Pso = Retained<ProtocolObject<dyn MTLComputePipelineState>>;
pub type CmdBuf = Retained<ProtocolObject<dyn MTLCommandBuffer>>;
pub fn wait_all<T>(
commands: impl IntoIterator<Item = T>,
mut wait: impl FnMut(T) -> Result<(), String>,
) -> Result<(), String> {
let mut result = Ok(());
for command in commands {
result = result.and(wait(command));
}
result
}
pub fn wait_or_drain<T>(
first: T,
pending: impl IntoIterator<Item = T>,
mut wait: impl FnMut(T) -> Result<(), String>,
) -> Result<(), String> {
if let Err(error) = wait(first) {
let _ = wait_all(pending, wait);
return Err(error);
}
Ok(())
}
#[cfg(test)]
std::thread_local! {
static INJECTED_WAIT_FAILURE: std::cell::Cell<Option<(&'static str, usize)>> = const { std::cell::Cell::new(None) };
static WAIT_STAGE_CALLS: std::cell::RefCell<HashMap<String, usize>> = std::cell::RefCell::new(HashMap::new());
}
#[cfg(test)]
pub fn inject_wait_failure(stage: &'static str, failing_call_index: usize) {
WAIT_STAGE_CALLS.with(|m| m.borrow_mut().clear());
INJECTED_WAIT_FAILURE.with(|f| f.set(Some((stage, failing_call_index))));
}
#[cfg(test)]
pub fn clear_wait_failure() {
WAIT_STAGE_CALLS.with(|m| m.borrow_mut().clear());
INJECTED_WAIT_FAILURE.with(|f| f.set(None));
}
pub fn wait_completed(cb: &CmdBuf, stage: &str, pos: usize) -> Result<(), String> {
cb.waitUntilCompleted();
#[cfg(test)]
if let Some((want_stage, want_idx)) = INJECTED_WAIT_FAILURE.with(|f| f.get()) {
if stage == want_stage {
let idx = WAIT_STAGE_CALLS.with(|m| {
let mut map = m.borrow_mut();
let c = map.entry(stage.to_string()).or_insert(0);
let cur = *c;
*c += 1;
cur
});
if idx == want_idx {
INJECTED_WAIT_FAILURE.with(|f| f.set(None));
return Err(format!("Metal {stage} at token {pos} failed (InjectedTestError)"));
}
}
}
let status = cb.status();
if status == MTLCommandBufferStatus::Completed { return Ok(()); }
let detail = cb.error().map(|err| format!(": {}", err.localizedDescription())).unwrap_or_default();
Err(format!("Metal {stage} at token {pos} failed ({status:?}){detail}"))
}
pub struct Gpu {
pub dev: Retained<ProtocolObject<dyn MTLDevice>>,
pub queue: Retained<ProtocolObject<dyn MTLCommandQueue>>,
lib: Retained<ProtocolObject<dyn MTLLibrary>>,
psos: std::cell::RefCell<HashMap<String, Pso>>,
}
impl Gpu {
pub fn new(src: &str, kernels: &[&str]) -> Gpu {
Self::new_with_lang(src, kernels, true)
}
pub fn new_with_lang(src: &str, kernels: &[&str], metal4: bool) -> Gpu {
let dev = MTLCreateSystemDefaultDevice().expect("no Metal device");
let queue = dev.newCommandQueue().expect("queue");
let opts = MTLCompileOptions::new();
opts.setMathMode(MTLMathMode::Safe);
opts.setLanguageVersion(if metal4 { MTLLanguageVersion::Version4_0 } else { MTLLanguageVersion::Version3_2 });
let lib = dev
.newLibraryWithSource_options_error(&NSString::from_str(src), Some(&opts))
.unwrap_or_else(|e| panic!("Metal compile failed:\n{}", e.localizedDescription()));
let g = Gpu { dev, queue, lib, psos: Default::default() };
for k in kernels { g.pso(k); }
g
}
pub fn pso(&self, name: &str) -> Pso {
trace_push(name);
if let Some(p) = self.psos.borrow().get(name) { return p.clone(); }
let f = self.lib.newFunctionWithName(&NSString::from_str(name)).unwrap_or_else(|| panic!("kernel {name} missing"));
let p = self.dev.newComputePipelineStateWithFunction_error(&f).unwrap_or_else(|e| panic!("pso {name}: {}", e.localizedDescription()));
pso_names().lock().unwrap().insert(Retained::as_ptr(&p) as *const c_void as usize, name.to_string());
self.psos.borrow_mut().insert(name.to_string(), p.clone());
p
}
pub fn buffer(&self, len: usize) -> Buf {
self.dev.newBufferWithLength_options(len.max(16), MTLResourceOptions::StorageModeShared).expect("alloc buffer")
}
pub fn buffer_with(&self, data: &[u8]) -> Buf {
let b = self.buffer(data.len());
unsafe { std::ptr::copy_nonoverlapping(data.as_ptr(), b.contents().as_ptr() as *mut u8, data.len()); }
b
}
pub fn buffer_nocopy(&self, ptr: *mut u8, len: usize) -> Buf {
unsafe {
self.dev
.newBufferWithBytesNoCopy_length_options_deallocator(
NonNull::new(ptr as *mut c_void).unwrap(), len, MTLResourceOptions::StorageModeShared, None)
.expect("no-copy buffer (needs page-aligned ptr/len)")
}
}
pub fn cmd(&self) -> CmdBuf { self.queue.commandBufferWithUnretainedReferences().expect("cmdbuf") }
pub fn recommended_max_working_set_size(&self) -> u64 {
self.dev.recommendedMaxWorkingSetSize()
}
pub fn current_allocated_size(&self) -> usize {
self.dev.currentAllocatedSize()
}
}
pub static BARRIERS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
pub static DISPATCHES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
fn pso_names() -> &'static std::sync::Mutex<HashMap<usize, String>> {
static M: std::sync::OnceLock<std::sync::Mutex<HashMap<usize, String>>> = std::sync::OnceLock::new();
M.get_or_init(Default::default)
}
#[derive(Clone, Debug, PartialEq)]
pub struct ProfSeg {
pub kernel: String,
pub tag: Option<u32>,
pub dispatches: usize,
pub ticks: Option<(u64, u64)>,
}
const PROF_SAMPLES_PER_BUF: usize = 4096;
struct ProfState {
sbs: Vec<Retained<ProtocolObject<dyn MTLCounterSampleBuffer>>>,
next: usize,
segs: Vec<ProfSeg>,
idx: Vec<Option<usize>>,
}
std::thread_local! {
static PROF: std::cell::RefCell<Option<ProfState>> = const { std::cell::RefCell::new(None) };
}
pub fn prof_arm(dev: &ProtocolObject<dyn MTLDevice>, max_encoders: usize) -> Result<(), String> {
if !dev.supportsCounterSampling(MTLCounterSamplingPoint::AtStageBoundary) {
return Err("this GPU cannot sample timestamps at encoder boundaries".into());
}
let sets = dev.counterSets().ok_or("no GPU counter sets")?;
let want = unsafe { MTLCommonCounterSetTimestamp };
let set = (0..sets.count())
.map(|i| sets.objectAtIndex(i))
.find(|s| s.name().to_string() == want.to_string())
.ok_or("no timestamp counter set")?;
let d = MTLCounterSampleBufferDescriptor::new();
d.setCounterSet(Some(&set));
d.setStorageMode(MTLStorageMode::Shared);
unsafe { d.setSampleCount(PROF_SAMPLES_PER_BUF) };
let sbs = (0..(2 * max_encoders).div_ceil(PROF_SAMPLES_PER_BUF).max(1))
.map(|_| dev.newCounterSampleBufferWithDescriptor_error(&d).map_err(|e| format!("counter sample buffer: {}", e.localizedDescription())))
.collect::<Result<Vec<_>, _>>()?;
PROF.with(|p| *p.borrow_mut() = Some(ProfState { sbs, next: 0, segs: Vec::new(), idx: Vec::new() }));
Ok(())
}
pub fn prof_take() -> Vec<ProfSeg> {
let Some(st) = PROF.with(|p| p.borrow_mut().take()) else { return Vec::new() };
let mut ts: Vec<u64> = Vec::with_capacity(st.next);
for (b, sb) in st.sbs.iter().enumerate() {
let n = st.next.saturating_sub(b * PROF_SAMPLES_PER_BUF).min(PROF_SAMPLES_PER_BUF);
if n == 0 {
break;
}
let data = unsafe { sb.resolveCounterRange(objc2_foundation::NSRange::new(0, n)) };
let mut v: Vec<u64> = data.map(|d| d.to_vec().as_chunks::<8>().0.iter().map(|c| u64::from_le_bytes(*c)).collect()).unwrap_or_default();
v.resize(n, u64::MAX);
ts.extend(v);
}
let mut segs = st.segs;
for (s, i) in segs.iter_mut().zip(&st.idx) {
s.ticks = i.and_then(|i| {
let (a, b) = (*ts.get(i)?, *ts.get(i + 1)?);
(a != u64::MAX && b != u64::MAX && a != 0 && b >= a).then_some((a, b))
});
}
segs
}
fn new_encoder(cb: &CmdBuf) -> (Retained<ProtocolObject<dyn MTLComputeCommandEncoder>>, usize) {
let timed = PROF.with(|p| {
let mut p = p.borrow_mut();
let st = p.as_mut()?;
let slot = (st.next + 2 <= st.sbs.len() * PROF_SAMPLES_PER_BUF).then_some(st.next);
if slot.is_some() {
st.next += 2;
}
st.segs.push(ProfSeg { kernel: String::new(), tag: None, dispatches: 0, ticks: None });
st.idx.push(slot);
let at = slot.map(|i| (st.sbs[i / PROF_SAMPLES_PER_BUF].clone(), i % PROF_SAMPLES_PER_BUF));
Some((at, st.segs.len() - 1))
});
match timed {
None => (cb.computeCommandEncoderWithDispatchType(MTLDispatchType::Concurrent).expect("encoder"), 0),
Some((at, seg)) => {
let d = MTLComputePassDescriptor::computePassDescriptor();
d.setDispatchType(MTLDispatchType::Concurrent);
if let Some((sb, i)) = at {
let a = unsafe { d.sampleBufferAttachments().objectAtIndexedSubscript(0) };
a.setSampleBuffer(Some(&sb));
unsafe {
a.setStartOfEncoderSampleIndex(i);
a.setEndOfEncoderSampleIndex(i + 1);
}
}
(cb.computeCommandEncoderWithDescriptor(&d).expect("encoder"), seg)
}
}
}
#[derive(Default)]
struct EncProf {
cb: Option<CmdBuf>,
seg: std::cell::Cell<usize>,
tag: std::cell::Cell<Option<u32>>,
bufs: std::cell::RefCell<HashMap<usize, (Buf, usize)>>,
bytes: std::cell::RefCell<HashMap<usize, Vec<u8>>>,
}
pub struct Enc {
e: std::cell::RefCell<Retained<ProtocolObject<dyn MTLComputeCommandEncoder>>>,
prof: Option<Box<EncProf>>,
}
impl Enc {
pub fn new(cb: &CmdBuf) -> Enc {
let armed = PROF.with(|p| p.borrow().is_some());
let (e, seg) = new_encoder(cb);
let prof = armed.then(|| Box::new(EncProf { cb: Some(cb.clone()), seg: seg.into(), ..Default::default() }));
Enc { e: std::cell::RefCell::new(e), prof }
}
#[inline] pub fn tag(&self, cls: u32) {
if let Some(p) = &self.prof { p.tag.set(Some(cls)); }
}
#[inline] pub fn pso(&self, p: &Pso) {
if let Some(pr) = &self.prof { self.prof_split(pr, p); }
self.e.borrow().setComputePipelineState(p);
}
fn prof_split(&self, pr: &EncProf, p: &Pso) {
let kernel = pso_names().lock().unwrap().get(&(Retained::as_ptr(p) as *const c_void as usize)).cloned().unwrap_or_else(|| "?".into());
let tag = pr.tag.take();
let split = PROF.with(|s| {
let mut s = s.borrow_mut();
let Some(st) = s.as_mut() else { return false };
let cur = &mut st.segs[pr.seg.get()];
if cur.dispatches == 0 || (cur.kernel == kernel && cur.tag == tag) {
cur.kernel = kernel.clone();
cur.tag = tag;
cur.dispatches += 1;
false
} else {
true
}
});
if !split { return; }
let cb = pr.cb.as_ref().unwrap();
self.e.borrow().endEncoding();
let (ne, seg) = new_encoder(cb);
pr.seg.set(seg);
PROF.with(|s| {
if let Some(st) = s.borrow_mut().as_mut() {
let cur = &mut st.segs[seg];
cur.kernel = kernel;
cur.tag = tag;
cur.dispatches = 1;
}
});
*self.e.borrow_mut() = ne;
let e = self.e.borrow();
for (&idx, (b, off)) in pr.bufs.borrow().iter() {
unsafe { e.setBuffer_offset_atIndex(Some(b), *off, idx); }
}
for (&idx, v) in pr.bytes.borrow().iter() {
unsafe { e.setBytes_length_atIndex(NonNull::new(v.as_ptr() as *mut c_void).unwrap(), v.len(), idx); }
}
}
#[inline] pub fn buf(&self, b: &Buf, off: usize, idx: usize) {
if let Some(p) = &self.prof { p.bufs.borrow_mut().insert(idx, (b.clone(), off)); }
unsafe { self.e.borrow().setBuffer_offset_atIndex(Some(b), off, idx); }
}
#[inline] pub fn bytes<T>(&self, v: &T, idx: usize) {
if let Some(p) = &self.prof {
let raw = unsafe { std::slice::from_raw_parts(v as *const T as *const u8, std::mem::size_of::<T>()) };
p.bytes.borrow_mut().insert(idx, raw.to_vec());
}
unsafe { self.e.borrow().setBytes_length_atIndex(NonNull::new(v as *const T as *mut c_void).unwrap(), std::mem::size_of::<T>(), idx); }
}
#[inline] pub fn bytes_slice<T>(&self, v: &[T], idx: usize) {
if let Some(p) = &self.prof {
let raw = unsafe { std::slice::from_raw_parts(v.as_ptr() as *const u8, std::mem::size_of_val(v)) };
p.bytes.borrow_mut().insert(idx, raw.to_vec());
}
unsafe { self.e.borrow().setBytes_length_atIndex(NonNull::new(v.as_ptr() as *mut c_void).unwrap(), std::mem::size_of_val(v), idx); }
}
#[inline] pub fn dispatch(&self, grid: (usize, usize, usize), tg: usize) {
DISPATCHES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
self.e.borrow().dispatchThreadgroups_threadsPerThreadgroup(
MTLSize { width: grid.0, height: grid.1, depth: grid.2 }, MTLSize { width: tg, height: 1, depth: 1 });
}
#[inline] pub fn dispatch_indirect(&self, b: &Buf, off: usize, tg: usize) {
DISPATCHES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
unsafe { self.e.borrow().dispatchThreadgroupsWithIndirectBuffer_indirectBufferOffset_threadsPerThreadgroup(b, off, MTLSize { width: tg, height: 1, depth: 1 }); }
}
#[inline] pub fn barrier(&self) { trace_push("|"); BARRIERS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); self.e.borrow().memoryBarrierWithScope(MTLBarrierScope::Buffers); }
pub fn end(self) { self.e.borrow().endEncoding(); }
}
#[cfg(test)]
mod prof_tests {
use super::*;
const SRC: &str = "#include <metal_stdlib>\nusing namespace metal;\n\
kernel void t_add(device uint *a [[buffer(0)]], constant uint &k [[buffer(5)]], uint i [[thread_position_in_grid]]) { a[i] += k; }\n\
kernel void t_mul(device uint *a [[buffer(0)]], constant uint &k [[buffer(5)]], uint i [[thread_position_in_grid]]) { a[i] *= k; }\n";
fn run(g: &Gpu, buf: &Buf) {
let cb = g.cmd();
let e = Enc::new(&cb);
e.buf(buf, 0, 0);
for (k, (name, tag)) in [("t_add", 7u32), ("t_add", 7), ("t_mul", 8), ("t_add", 7)].iter().enumerate() {
e.tag(*tag);
e.pso(&g.pso(name));
e.bytes(&[[1u32, 2, 3, 4][k]], 5);
e.dispatch((1, 1, 1), 256);
e.barrier();
}
e.end();
cb.commit();
cb.waitUntilCompleted();
}
#[test]
fn profiled_encoder_split_keeps_results_and_times_each_kernel_run() {
let g = Gpu::new_with_lang(SRC, &["t_add", "t_mul"], false);
let words = |b: &Buf| unsafe { std::slice::from_raw_parts(b.contents().as_ptr() as *const u32, 256).to_vec() };
let plain = g.buffer_with(&[0u8; 1024]);
run(&g, &plain);
assert!(words(&plain).iter().all(|&w| w == 13)); if prof_arm(&g.dev, 16).is_err() {
return; }
let profiled = g.buffer_with(&[0u8; 1024]);
run(&g, &profiled);
let segs = prof_take();
assert_eq!(words(&profiled), words(&plain));
let runs: Vec<(&str, Option<u32>, usize)> = segs.iter().map(|s| (s.kernel.as_str(), s.tag, s.dispatches)).collect();
assert_eq!(runs, vec![("t_add", Some(7), 2), ("t_mul", Some(8), 1), ("t_add", Some(7), 1)]);
assert!(segs.iter().all(|s| s.ticks.is_some()), "{segs:?}");
assert!(prof_take().is_empty());
let again = g.buffer_with(&[0u8; 1024]);
run(&g, &again);
assert!(prof_take().is_empty());
}
}
static TRACING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
thread_local! {
static TRACE: std::cell::RefCell<Vec<&'static str>> = const { std::cell::RefCell::new(Vec::new()) };
static TRACE_NAMES: std::cell::RefCell<HashMap<String, &'static str>> = std::cell::RefCell::new(HashMap::new());
}
#[inline]
fn trace_push(name: &str) {
if !TRACING.load(std::sync::atomic::Ordering::Relaxed) {
return;
}
let s = TRACE_NAMES.with(|m| {
*m.borrow_mut().entry(name.to_string()).or_insert_with(|| Box::leak(name.to_string().into_boxed_str()))
});
TRACE.with(|t| t.borrow_mut().push(s));
}
pub fn trace_begin() {
TRACE.with(|t| t.borrow_mut().clear());
TRACING.store(true, std::sync::atomic::Ordering::Relaxed);
}
pub fn trace_take() -> Vec<&'static str> {
TRACING.store(false, std::sync::atomic::Ordering::Relaxed);
TRACE.with(|t| std::mem::take(&mut *t.borrow_mut()))
}