Skip to main content

caroli_gpu/
metal.rs

1//! Metal backend (`common.metal`, `chebyshev.metal`, `walk.metal`). The kernels are compiled from source when the device is
2//! opened, without fast math (the double-single arithmetic needs exact IEEE rounding). Buffers
3//! live in shared memory: on Apple Silicon the CPU reads the results without a copy.
4
5use 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
22/// Threads per threadgroup (`GROUP` in the kernels).
23pub(crate) const GROUP: usize = 256;
24
25/// Dispatches encoded per command buffer.
26const 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/// `Params` of the kernels.
34#[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
53/// The GPU, its command queue and the compiled kernels.
54pub struct MetalDevice {
55    device: Retained<ProtocolObject<dyn MTLDevice>>,
56    queue: Retained<ProtocolObject<dyn objc2_metal::MTLCommandQueue>>,
57    single: Kernels,
58    double_single: Kernels,
59    /// Row probabilities of an f32 walk state, added to an accumulator.
60    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
67/// Floats per complex number.
68pub(crate) fn width(precision: Precision) -> usize {
69    match precision {
70        Precision::Single => 2,
71        Precision::DoubleSingle => 4,
72    }
73}
74
75/// `x = hi + lo` with two f32.
76fn 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    /// The default GPU with the kernels compiled. Fails where there is no GPU (virtual
118    /// machines, some CI runners).
119    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    /// The GPU's name, e.g. "Apple M5".
164    pub fn name(&self) -> String {
165        self.device.name().to_string()
166    }
167
168    /// Largest buffer the device can allocate, in bytes.
169    pub fn max_buffer_length(&self) -> usize {
170        self.device.maxBufferLength()
171    }
172
173    /// Runs `dispatches` encoded by `encode_one(encoder, index)`, `BATCH` per command buffer,
174    /// and waits for the last. The dispatches of an encoder run one after the other.
175    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        // Command buffers of one queue complete in order: wait for the last, then check all.
198        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        // SAFETY: `pointer` is valid for `bytes` bytes, which Metal copies before returning.
223        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    /// Uploads a rescaled Hamiltonian `H̃` (spectrum in (−1, 1)).
240    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
256/// A sparse Hamiltonian resident on the GPU.
257pub 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
266/// Binds buffers from index 0 and `bytes` after them.
267///
268/// # Safety
269///
270/// The arguments must be those the kernel expects, and the buffers must outlive the command
271/// buffer.
272pub(crate) unsafe fn bind(encoder: &Encoder, buffers: &[&Buffer], bytes: &[(NonNull<c_void>, usize)]) {
273    for (i, b) in buffers.iter().enumerate() {
274        // SAFETY: per the caller.
275        unsafe { encoder.setBuffer_offset_atIndex(Some(&***b), 0, i) };
276    }
277    for (j, (pointer, length)) in bytes.iter().enumerate() {
278        // SAFETY: per the caller; Metal copies the bytes when encoding.
279        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        // SAFETY: the buffer holds at least `floats` f32 written by completed commands.
299        let data = unsafe { std::slice::from_raw_parts(buffer.contents().as_ptr() as *const f32, floats) };
300        decode(data, self.precision)
301    }
302
303    /// KPM moments `μ_n = kernel_n · mean_r ⟨r| T_n(H̃) |r⟩`, `n = 0..kernel.len()`, all start
304    /// vectors at once, with the doubling relations (as `caroli_kpm::block_moments`).
305    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        // Per-threadgroup shares of the current step, then the reduced sums of every step.
321        let partials = self.gpu.buffer(self.bytes(2 * groups))?;
322        // The sums are always double-single (4 floats per complex).
323        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                // SAFETY: `kpm_step(row_ptr, cols, vals, prev, cur, next, partials, params)`; the
338                // buffers live until `run` returns.
339                unsafe {
340                    bind(
341                        encoder,
342                        &[&self.row_ptr, &self.cols, &self.vals, prev, cur, next, &partials],
343                        &[as_bytes(&params)],
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                // SAFETY: `reduce_partials(partials, sums, params)`.
351                unsafe { bind(encoder, &[&partials, &sums], &[as_bytes(&params)]) };
352                encoder.dispatchThreadgroups_threadsPerThreadgroup(threadgroups(1), GROUP_SIZE);
353            }
354        })?;
355        // SAFETY: `sums` holds 2·steps double-single complex numbers written by the kernels.
356        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    /// `steps` propagation steps `ψ ← Σ_n c_n T_n(H̃) ψ` (coefficients from
365    /// `caroli_dynamics::Chebyshev`) for a block of `vectors` wave functions stored
366    /// interleaved (`ψ[row·vectors + v]`, as `SparseMatrix::apply_block`).
367    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        // Buffers: three Chebyshev terms and the accumulator; T_0 and the accumulator swap
383        // roles after each step.
384        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        // Per step: one init dispatch and `terms − 1` Chebyshev dispatches.
399        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                // SAFETY: `propagate_init(cur, psi, coefficient, params)`.
411                unsafe { bind(encoder, &[&b[t0], &b[acc]], &[c, as_bytes(&params)]) };
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                // SAFETY: `propagate_step(row_ptr, cols, vals, prev, cur, next, psi, coefficient,
424                // params)`.
425                unsafe {
426                    bind(
427                        encoder,
428                        &[&self.row_ptr, &self.cols, &self.vals, prev, cur, next, &b[acc]],
429                        &[c, as_bytes(&params)],
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}