1use crate::{GpuError, Precision, doubled_moments};
6use caroli_model::{SparseMatrix, c64};
7use objc2::rc::Retained;
8use objc2::runtime::{NSObjectProtocol, ProtocolObject};
9use objc2::sel;
10use objc2_foundation::NSString;
11use objc2_metal::{
12 MTLBuffer, MTLCommandBuffer, MTLCommandEncoder, MTLCommandQueue, MTLCompileOptions,
13 MTLComputeCommandEncoder, MTLComputePipelineState, MTLCreateSystemDefaultDevice, MTLDevice, MTLLibrary,
14 MTLMathMode, MTLResourceOptions, MTLSize,
15};
16use std::ffi::c_void;
17use std::ptr::NonNull;
18
19const SOURCE: &str =
20 concat!(include_str!("common.metal"), include_str!("chebyshev.metal"), include_str!("walk.metal"));
21
22pub(crate) const GROUP: usize = 256;
24
25const BATCH: usize = 256;
27
28pub(crate) type Buffer = Retained<ProtocolObject<dyn MTLBuffer>>;
29pub(crate) type Pipeline = Retained<ProtocolObject<dyn MTLComputePipelineState>>;
30pub(crate) type Encoder = Retained<ProtocolObject<dyn MTLComputeCommandEncoder>>;
31type Commands = Retained<ProtocolObject<dyn MTLCommandBuffer>>;
32
33#[repr(C)]
35#[derive(Clone, Copy)]
36struct Params {
37 n: u32,
38 vectors: u32,
39 total: u32,
40 first: u32,
41 slot: u32,
42}
43
44pub(crate) struct Kernels {
45 kpm_step: Pipeline,
46 reduce_partials: Pipeline,
47 propagate_step: Pipeline,
48 propagate_init: Pipeline,
49 pub(crate) walk_coin: Pipeline,
50 pub(crate) walk_edge: Pipeline,
51}
52
53pub struct MetalDevice {
55 device: Retained<ProtocolObject<dyn MTLDevice>>,
56 queue: Retained<ProtocolObject<dyn objc2_metal::MTLCommandQueue>>,
57 single: Kernels,
58 double_single: Kernels,
59 pub(crate) walk_accumulate: Pipeline,
61}
62
63pub(crate) fn backend(context: &str, error: &objc2_foundation::NSError) -> GpuError {
64 GpuError::Backend(format!("{context}: {}", error.localizedDescription()))
65}
66
67pub(crate) fn width(precision: Precision) -> usize {
69 match precision {
70 Precision::Single => 2,
71 Precision::DoubleSingle => 4,
72 }
73}
74
75fn split(x: f64) -> [f32; 2] {
77 let hi = x as f32;
78 [hi, (x - hi as f64) as f32]
79}
80
81pub(crate) fn encode(z: &[c64], precision: Precision) -> Vec<f32> {
82 match precision {
83 Precision::Single => z.iter().flat_map(|v| [v.re as f32, v.im as f32]).collect(),
84 Precision::DoubleSingle => z
85 .iter()
86 .flat_map(|v| {
87 let (re, im) = (split(v.re), split(v.im));
88 [re[0], re[1], im[0], im[1]]
89 })
90 .collect(),
91 }
92}
93
94pub(crate) fn decode(data: &[f32], precision: Precision) -> Vec<c64> {
95 match precision {
96 Precision::Single => {
97 data.as_chunks::<2>().0.iter().map(|&[re, im]| c64::new(re as f64, im as f64)).collect()
98 }
99 Precision::DoubleSingle => data
100 .as_chunks::<4>()
101 .0
102 .iter()
103 .map(|&[re_hi, re_lo, im_hi, im_lo]| {
104 c64::new(re_hi as f64 + re_lo as f64, im_hi as f64 + im_lo as f64)
105 })
106 .collect(),
107 }
108}
109
110pub(crate) fn threadgroups(total: usize) -> MTLSize {
111 MTLSize { width: total.div_ceil(GROUP), height: 1, depth: 1 }
112}
113
114pub(crate) const GROUP_SIZE: MTLSize = MTLSize { width: GROUP, height: 1, depth: 1 };
115
116impl MetalDevice {
117 pub fn new() -> Result<Self, GpuError> {
120 let device =
121 MTLCreateSystemDefaultDevice().ok_or_else(|| GpuError::Unavailable("no Metal device".into()))?;
122 let options = MTLCompileOptions::new();
123 if options.respondsToSelector(sel!(setMathMode:)) {
124 options.setMathMode(MTLMathMode::Safe);
125 } else {
126 #[allow(deprecated)]
127 options.setFastMathEnabled(false);
128 }
129 let library = device
130 .newLibraryWithSource_options_error(&NSString::from_str(SOURCE), Some(&options))
131 .map_err(|e| backend("compiling the Metal kernels", &e))?;
132 let pipeline = |name: &str| -> Result<Pipeline, GpuError> {
133 let function = library
134 .newFunctionWithName(&NSString::from_str(name))
135 .ok_or_else(|| GpuError::Backend(format!("kernel `{name}` not found")))?;
136 let p = device
137 .newComputePipelineStateWithFunction_error(&function)
138 .map_err(|e| backend(&format!("building the {name} pipeline"), &e))?;
139 if p.maxTotalThreadsPerThreadgroup() < GROUP {
140 return Err(GpuError::Backend(format!(
141 "{name}: {} threads per group, {GROUP} needed",
142 p.maxTotalThreadsPerThreadgroup()
143 )));
144 }
145 Ok(p)
146 };
147 let kernels = |suffix: &str| -> Result<Kernels, GpuError> {
148 Ok(Kernels {
149 kpm_step: pipeline(&format!("kpm_step_{suffix}"))?,
150 reduce_partials: pipeline(&format!("reduce_partials_{suffix}"))?,
151 propagate_step: pipeline(&format!("propagate_step_{suffix}"))?,
152 propagate_init: pipeline(&format!("propagate_init_{suffix}"))?,
153 walk_coin: pipeline(&format!("walk_coin_{suffix}"))?,
154 walk_edge: pipeline(&format!("walk_edge_{suffix}"))?,
155 })
156 };
157 let (single, double_single) = (kernels("f32")?, kernels("df64")?);
158 let walk_accumulate = pipeline("walk_accumulate_f32")?;
159 let queue = device.newCommandQueue().ok_or_else(|| GpuError::Backend("no command queue".into()))?;
160 Ok(Self { device, queue, single, double_single, walk_accumulate })
161 }
162
163 pub fn name(&self) -> String {
165 self.device.name().to_string()
166 }
167
168 pub fn max_buffer_length(&self) -> usize {
170 self.device.maxBufferLength()
171 }
172
173 pub(crate) fn run(
176 &self,
177 context: &str,
178 dispatches: usize,
179 mut encode_one: impl FnMut(&Encoder, usize),
180 ) -> Result<(), GpuError> {
181 let mut submitted: Vec<Commands> = Vec::new();
182 let mut index = 0;
183 while index < dispatches {
184 let commands =
185 self.queue.commandBuffer().ok_or_else(|| GpuError::Backend("no command buffer".into()))?;
186 let encoder = commands
187 .computeCommandEncoder()
188 .ok_or_else(|| GpuError::Backend("no compute encoder".into()))?;
189 for i in index..(index + BATCH).min(dispatches) {
190 encode_one(&encoder, i);
191 }
192 encoder.endEncoding();
193 commands.commit();
194 index += BATCH;
195 submitted.push(commands);
196 }
197 if let Some(last) = submitted.last() {
199 last.waitUntilCompleted();
200 }
201 for commands in &submitted {
202 if let Some(error) = commands.error() {
203 return Err(backend(context, &error));
204 }
205 }
206 Ok(())
207 }
208
209 pub(crate) fn kernels(&self, precision: Precision) -> &Kernels {
210 match precision {
211 Precision::Single => &self.single,
212 Precision::DoubleSingle => &self.double_single,
213 }
214 }
215
216 pub(crate) fn buffer_from<T: Copy>(&self, data: &[T]) -> Result<Buffer, GpuError> {
217 let bytes = std::mem::size_of_val(data);
218 if bytes == 0 {
219 return self.buffer(4);
220 }
221 let pointer = NonNull::new(data.as_ptr() as *mut c_void).expect("slice pointer");
222 unsafe {
224 self.device.newBufferWithBytes_length_options(
225 pointer,
226 bytes,
227 MTLResourceOptions::StorageModeShared,
228 )
229 }
230 .ok_or_else(|| GpuError::Backend(format!("allocating a {bytes}-byte buffer")))
231 }
232
233 pub(crate) fn buffer(&self, bytes: usize) -> Result<Buffer, GpuError> {
234 self.device
235 .newBufferWithLength_options(bytes.max(4), MTLResourceOptions::StorageModeShared)
236 .ok_or_else(|| GpuError::Backend(format!("allocating a {bytes}-byte buffer")))
237 }
238
239 pub fn upload(&self, h: &SparseMatrix, precision: Precision) -> Result<MetalOperator<'_>, GpuError> {
241 let to_u32 = |x: usize| {
242 u32::try_from(x).map_err(|_| GpuError::Backend("matrix too large for u32 indices".into()))
243 };
244 let row_ptr = h.row_ptr.iter().map(|&x| to_u32(x)).collect::<Result<Vec<u32>, _>>()?;
245 Ok(MetalOperator {
246 gpu: self,
247 precision,
248 n: h.n,
249 row_ptr: self.buffer_from(&row_ptr)?,
250 cols: self.buffer_from(&h.cols)?,
251 vals: self.buffer_from(&encode(&h.vals, precision))?,
252 })
253 }
254}
255
256pub struct MetalOperator<'a> {
258 gpu: &'a MetalDevice,
259 precision: Precision,
260 n: usize,
261 row_ptr: Buffer,
262 cols: Buffer,
263 vals: Buffer,
264}
265
266pub(crate) unsafe fn bind(encoder: &Encoder, buffers: &[&Buffer], bytes: &[(NonNull<c_void>, usize)]) {
273 for (i, b) in buffers.iter().enumerate() {
274 unsafe { encoder.setBuffer_offset_atIndex(Some(&***b), 0, i) };
276 }
277 for (j, (pointer, length)) in bytes.iter().enumerate() {
278 unsafe { encoder.setBytes_length_atIndex(*pointer, *length, buffers.len() + j) };
280 }
281}
282
283pub(crate) fn as_bytes<T>(value: &T) -> (NonNull<c_void>, usize) {
284 (NonNull::from(value).cast(), std::mem::size_of::<T>())
285}
286
287impl MetalOperator<'_> {
288 fn bytes(&self, entries: usize) -> usize {
289 entries * width(self.precision) * std::mem::size_of::<f32>()
290 }
291
292 fn run(&self, dispatches: usize, encode_one: impl FnMut(&Encoder, usize)) -> Result<(), GpuError> {
293 self.gpu.run("running the Chebyshev kernels", dispatches, encode_one)
294 }
295
296 fn read(&self, buffer: &Buffer, entries: usize) -> Vec<c64> {
297 let floats = entries * width(self.precision);
298 let data = unsafe { std::slice::from_raw_parts(buffer.contents().as_ptr() as *const f32, floats) };
300 decode(data, self.precision)
301 }
302
303 pub fn kpm_moments(&self, starts: &[Vec<c64>], kernel: &[f64]) -> Result<Vec<c64>, GpuError> {
306 let (n, vectors) = (self.n, starts.len());
307 assert!(vectors > 0, "no start vectors");
308 assert!(starts.iter().all(|s| s.len() == n), "start vectors must have {n} entries");
309 assert!(kernel.len() >= 2, "at least two moments");
310 let total = n * vectors;
311 let total32 = u32::try_from(total).map_err(|_| GpuError::Backend("too many entries".into()))?;
312 let block: Vec<c64> = (0..total).map(|i| starts[i % vectors][i / vectors]).collect();
313 let t = [
314 self.gpu.buffer_from(&encode(&block, self.precision))?,
315 self.gpu.buffer(self.bytes(total))?,
316 self.gpu.buffer(self.bytes(total))?,
317 ];
318 let groups = total.div_ceil(GROUP);
319 let steps = kernel.len().div_ceil(2);
320 let partials = self.gpu.buffer(self.bytes(2 * groups))?;
322 let sums = self.gpu.buffer(2 * steps * 4 * std::mem::size_of::<f32>())?;
324 let kernels = self.gpu.kernels(self.precision);
325 self.run(2 * steps, |encoder, i| {
326 let s = i / 2;
327 if i % 2 == 0 {
328 let params = Params {
329 n: n as u32,
330 vectors: vectors as u32,
331 total: total32,
332 first: (s == 0) as u32,
333 slot: s as u32,
334 };
335 let (prev, cur, next) = (&t[(s + 2) % 3], &t[s % 3], &t[(s + 1) % 3]);
336 encoder.setComputePipelineState(&kernels.kpm_step);
337 unsafe {
340 bind(
341 encoder,
342 &[&self.row_ptr, &self.cols, &self.vals, prev, cur, next, &partials],
343 &[as_bytes(¶ms)],
344 )
345 };
346 encoder.dispatchThreadgroups_threadsPerThreadgroup(threadgroups(total), GROUP_SIZE);
347 } else {
348 let params = Params { n: groups as u32, vectors: 0, total: 0, first: 0, slot: s as u32 };
349 encoder.setComputePipelineState(&kernels.reduce_partials);
350 unsafe { bind(encoder, &[&partials, &sums], &[as_bytes(¶ms)]) };
352 encoder.dispatchThreadgroups_threadsPerThreadgroup(threadgroups(1), GROUP_SIZE);
353 }
354 })?;
355 let raw =
357 unsafe { std::slice::from_raw_parts(sums.contents().as_ptr() as *const f32, 2 * steps * 4) };
358 let all = decode(raw, Precision::DoubleSingle);
359 let s1: Vec<c64> = all.iter().step_by(2).copied().collect();
360 let s2: Vec<c64> = all.iter().skip(1).step_by(2).copied().collect();
361 Ok(doubled_moments(&s1, &s2, vectors, kernel))
362 }
363
364 pub fn propagate(
368 &self,
369 coefficients: &[c64],
370 psi: &mut [c64],
371 vectors: usize,
372 steps: usize,
373 ) -> Result<(), GpuError> {
374 let n = self.n;
375 assert!(
376 vectors > 0 && psi.len() == n * vectors,
377 "ψ must hold {vectors} wave functions of {n} entries"
378 );
379 assert!(coefficients.len() >= 2, "at least two coefficients");
380 let total = psi.len();
381 let total32 = u32::try_from(total).map_err(|_| GpuError::Backend("too many entries".into()))?;
382 let mut b = vec![self.gpu.buffer_from(&encode(psi, self.precision))?];
385 for _ in 0..3 {
386 b.push(self.gpu.buffer(self.bytes(total))?);
387 }
388 let coefficients = encode(coefficients, self.precision);
389 let w = width(self.precision);
390 let kernels = self.gpu.kernels(self.precision);
391 let terms = coefficients.len() / w;
392 let (mut t0, mut acc) = (0usize, 3usize);
393 let mut roles = Vec::with_capacity(steps);
394 for _ in 0..steps {
395 roles.push((t0, acc));
396 std::mem::swap(&mut t0, &mut acc);
397 }
398 self.run(steps * terms, |encoder, i| {
400 let (step, k) = (i / terms, i % terms);
401 let (t0, acc) = roles[step];
402 let others: Vec<usize> = (0..4).filter(|&j| j != t0 && j != acc).collect();
403 let t = [t0, others[0], others[1]];
404 let coefficient = &coefficients[k * w..(k + 1) * w];
405 let c = (NonNull::from(coefficient).cast(), std::mem::size_of_val(coefficient));
406 if k == 0 {
407 let params =
408 Params { n: n as u32, vectors: vectors as u32, total: total32, first: 0, slot: 0 };
409 encoder.setComputePipelineState(&kernels.propagate_init);
410 unsafe { bind(encoder, &[&b[t0], &b[acc]], &[c, as_bytes(¶ms)]) };
412 } else {
413 let s = k - 1;
414 let params = Params {
415 n: n as u32,
416 vectors: vectors as u32,
417 total: total32,
418 first: (s == 0) as u32,
419 slot: 0,
420 };
421 let (prev, cur, next) = (&b[t[(s + 2) % 3]], &b[t[s % 3]], &b[t[(s + 1) % 3]]);
422 encoder.setComputePipelineState(&kernels.propagate_step);
423 unsafe {
426 bind(
427 encoder,
428 &[&self.row_ptr, &self.cols, &self.vals, prev, cur, next, &b[acc]],
429 &[c, as_bytes(¶ms)],
430 )
431 };
432 }
433 encoder.dispatchThreadgroups_threadsPerThreadgroup(threadgroups(total), GROUP_SIZE);
434 })?;
435 psi.copy_from_slice(&self.read(&b[t0], total));
436 Ok(())
437 }
438}