1use crate::metal::{Buffer, GROUP_SIZE, MetalDevice, as_bytes, bind, encode, threadgroups, width};
6use crate::{GpuError, Precision};
7use caroli_model::c64;
8use objc2_metal::{MTLBuffer, MTLComputeCommandEncoder};
9use rayon::prelude::*;
10
11pub const MAX_DEGREE: usize = 8;
13
14#[repr(C)]
16#[derive(Clone, Copy)]
17struct WalkParams {
18 bits: u32,
19 nodes: u32,
20 edges: u32,
21 batch: u32,
22 coin_len: u32,
23}
24
25pub struct WalkTables<'a> {
27 pub bits: usize,
29 pub node_rows: &'a [usize],
31 pub coins: &'a [Vec<c64>],
33 pub halves: &'a [(usize, usize)],
35 pub exchange: [c64; 3],
38}
39
40pub struct MetalWalk<'a> {
42 gpu: &'a MetalDevice,
43 precision: Precision,
44 params: WalkParams,
45 entries: usize,
46 psi: Buffer,
47 node_rows: Buffer,
48 coin_at: Buffer,
49 coins: Buffer,
50 halves: Buffer,
51 exchange: Buffer,
52 acc: Buffer,
54 rows: usize,
56}
57
58fn to_u32(x: usize, what: &str) -> Result<u32, GpuError> {
59 u32::try_from(x)
60 .map_err(|_| GpuError::Backend(format!("{what} does not fit the kernels' 32-bit indices")))
61}
62
63impl MetalDevice {
64 pub fn walk(
66 &self,
67 tables: &WalkTables,
68 psi: &[c64],
69 precision: Precision,
70 ) -> Result<MetalWalk<'_>, GpuError> {
71 self.walks(std::slice::from_ref(tables), psi, precision)
72 }
73
74 pub fn walks(
77 &self,
78 batch: &[WalkTables],
79 psi: &[c64],
80 precision: Precision,
81 ) -> Result<MetalWalk<'_>, GpuError> {
82 let tables = batch.first().ok_or_else(|| GpuError::Backend("an empty batch".into()))?;
83 let nodes = tables.node_rows.len() - 1;
84 let edges = tables.halves.len();
85 let rows = tables.node_rows[nodes];
86 let bits = tables.bits;
87 if bits == 0 || bits != edges {
88 return Err(GpuError::Backend("one spin per edge, and at least one edge".into()));
89 }
90 if batch
91 .iter()
92 .any(|t| t.bits != bits || t.node_rows != tables.node_rows || t.halves != tables.halves)
93 {
94 return Err(GpuError::Backend("the walks of a batch must share their graph".into()));
95 }
96 if (0..nodes).any(|x| tables.node_rows[x + 1] - tables.node_rows[x] > MAX_DEGREE) {
97 return Err(GpuError::Backend(format!("node degrees above {MAX_DEGREE}")));
98 }
99 let entries = batch.len() * (rows << bits);
100 if psi.len() != entries {
101 return Err(GpuError::Backend(format!("state of {} entries, {entries} expected", psi.len())));
102 }
103 let bytes = entries * width(precision) * std::mem::size_of::<f32>();
104 if bytes > self.max_buffer_length() {
105 return Err(GpuError::Backend(format!(
106 "a state of {bytes} bytes exceeds the largest Metal buffer ({} bytes)",
107 self.max_buffer_length()
108 )));
109 }
110 to_u32(batch.len() * (nodes << bits), "the coin grid")?;
111 to_u32(entries, "the batch")?;
112 let node_rows: Vec<u32> =
113 tables.node_rows.iter().map(|&r| to_u32(r, "a row index")).collect::<Result<_, _>>()?;
114 let mut coin_at = Vec::with_capacity(nodes);
115 let mut coin_len = 0;
116 for x in 0..nodes {
117 let d = tables.node_rows[x + 1] - tables.node_rows[x];
118 coin_at.push(to_u32(coin_len, "the coin table")?);
119 coin_len += d * d;
120 }
121 let mut coins = Vec::with_capacity(batch.len() * coin_len);
122 for t in batch {
123 for (x, coin) in t.coins.iter().enumerate() {
124 let d = tables.node_rows[x + 1] - tables.node_rows[x];
125 if coin.len() != d * d {
126 return Err(GpuError::Backend(format!("node {x}: a {d} × {d} coin expected")));
127 }
128 coins.extend_from_slice(coin);
129 }
130 }
131 let exchange: Vec<c64> = batch.iter().flat_map(|t| t.exchange).collect();
132 let halves: Vec<[u32; 2]> = tables
133 .halves
134 .iter()
135 .map(|&(a, b)| Ok([to_u32(a, "a row index")?, to_u32(b, "a row index")?]))
136 .collect::<Result<_, GpuError>>()?;
137 let mut walk = MetalWalk {
138 gpu: self,
139 precision,
140 params: WalkParams {
141 bits: bits as u32,
142 nodes: nodes as u32,
143 edges: edges as u32,
144 batch: batch.len() as u32,
145 coin_len: to_u32(coin_len, "the coin table")?,
146 },
147 entries,
148 psi: self.buffer(bytes)?,
149 node_rows: self.buffer_from(&node_rows)?,
150 coin_at: self.buffer_from(&coin_at)?,
151 coins: self.buffer_from(&encode(&coins, precision))?,
152 halves: self.buffer_from(&halves)?,
153 exchange: self.buffer_from(&encode(&exchange, precision))?,
154 acc: self.buffer(batch.len() * rows * std::mem::size_of::<f32>())?,
155 rows: batch.len() * rows,
156 };
157 walk.set_state(psi);
158 walk.reset_accumulated();
159 Ok(walk)
160 }
161}
162
163impl MetalWalk<'_> {
164 pub fn precision(&self) -> Precision {
166 self.precision
167 }
168
169 fn floats(&self) -> &[f32] {
171 unsafe {
173 std::slice::from_raw_parts(
174 self.psi.contents().as_ptr() as *const f32,
175 self.entries * width(self.precision),
176 )
177 }
178 }
179
180 pub fn set_state(&mut self, psi: &[c64]) {
182 assert_eq!(psi.len(), self.entries, "state of the wrong dimension");
183 let w = width(self.precision);
184 let data = unsafe {
186 std::slice::from_raw_parts_mut(self.psi.contents().as_ptr() as *mut f32, self.entries * w)
187 };
188 let chunk = 1 << 16;
189 data.par_chunks_mut(chunk * w).zip(psi.par_chunks(chunk)).for_each(|(out, z)| {
190 out.copy_from_slice(&encode(z, self.precision));
191 });
192 }
193
194 pub fn state(&self) -> Vec<c64> {
196 let mut psi = vec![c64::new(0.0, 0.0); self.entries];
197 self.read_into(&mut psi);
198 psi
199 }
200
201 pub fn read_into(&self, psi: &mut [c64]) {
203 assert_eq!(psi.len(), self.entries, "state of the wrong dimension");
204 let (w, chunk) = (width(self.precision), 1 << 16);
205 let precision = self.precision;
206 psi.par_chunks_mut(chunk).zip(self.floats().par_chunks(chunk * w)).for_each(
207 |(z, f)| match precision {
208 Precision::Single => {
209 for (v, &[re, im]) in z.iter_mut().zip(f.as_chunks::<2>().0) {
210 *v = c64::new(re as f64, im as f64);
211 }
212 }
213 Precision::DoubleSingle => {
214 for (v, &[re_hi, re_lo, im_hi, im_lo]) in z.iter_mut().zip(f.as_chunks::<4>().0) {
215 *v = c64::new(re_hi as f64 + re_lo as f64, im_hi as f64 + im_lo as f64);
216 }
217 }
218 },
219 );
220 }
221
222 pub fn norm_sqr(&self) -> f64 {
224 let w = width(self.precision);
225 let precision = self.precision;
226 self.floats()
227 .par_chunks((1 << 16) * w)
228 .map(|f| match precision {
229 Precision::Single => f.iter().map(|&x| (x as f64) * (x as f64)).sum::<f64>(),
230 Precision::DoubleSingle => f
231 .as_chunks::<2>()
232 .0
233 .iter()
234 .map(|&[hi, lo]| {
235 let x = hi as f64 + lo as f64;
236 x * x
237 })
238 .sum(),
239 })
240 .sum()
241 }
242
243 pub fn row_probabilities(&self, rows: usize) -> Vec<f64> {
245 assert!(rows > 0 && self.entries.is_multiple_of(rows), "rows must divide the state");
246 let w = width(self.precision);
247 let precision = self.precision;
248 self.floats()
249 .par_chunks(self.entries / rows * w)
250 .map(|f| match precision {
251 Precision::Single => f.iter().map(|&x| (x as f64) * (x as f64)).sum::<f64>(),
252 Precision::DoubleSingle => f
253 .as_chunks::<2>()
254 .0
255 .iter()
256 .map(|&[hi, lo]| {
257 let x = hi as f64 + lo as f64;
258 x * x
259 })
260 .sum(),
261 })
262 .collect()
263 }
264
265 pub fn distance(&self, psi: &[c64]) -> f64 {
267 assert_eq!(psi.len(), self.entries, "state of the wrong dimension");
268 let (w, chunk) = (width(self.precision), 1 << 16);
269 let precision = self.precision;
270 self.floats()
271 .par_chunks(chunk * w)
272 .zip(psi.par_chunks(chunk))
273 .map(|(f, z)| match precision {
274 Precision::Single => f
275 .as_chunks::<2>()
276 .0
277 .iter()
278 .zip(z)
279 .map(|(&[re, im], v)| (c64::new(re as f64, im as f64) - v).norm_sqr())
280 .sum::<f64>(),
281 Precision::DoubleSingle => f
282 .as_chunks::<4>()
283 .0
284 .iter()
285 .zip(z)
286 .map(|(&[re_hi, re_lo, im_hi, im_lo], v)| {
287 (c64::new(re_hi as f64 + re_lo as f64, im_hi as f64 + im_lo as f64) - v).norm_sqr()
288 })
289 .sum(),
290 })
291 .sum::<f64>()
292 .sqrt()
293 }
294
295 pub fn steps_accumulate(&mut self, n: usize) -> Result<(), GpuError> {
299 if self.precision != Precision::Single {
300 return Err(GpuError::Backend("the accumulation takes f32 states".into()));
301 }
302 let kernels = self.gpu.kernels(self.precision);
303 let p = self.params;
304 let coin_threads = p.batch as usize * ((p.nodes as usize) << p.bits);
305 let edge_threads = p.batch as usize * ((p.edges as usize) << (p.bits - 1));
306 let entries = self.entries;
307 self.gpu.run("running the walk kernels", 3 * n, |encoder, i| match i % 3 {
308 0 => {
309 encoder.setComputePipelineState(&kernels.walk_coin);
310 unsafe {
312 bind(encoder, &[&self.psi, &self.node_rows, &self.coin_at, &self.coins], &[as_bytes(&p)])
313 };
314 encoder.dispatchThreadgroups_threadsPerThreadgroup(threadgroups(coin_threads), GROUP_SIZE);
315 }
316 1 => {
317 encoder.setComputePipelineState(&kernels.walk_edge);
318 unsafe { bind(encoder, &[&self.psi, &self.halves, &self.exchange], &[as_bytes(&p)]) };
320 encoder.dispatchThreadgroups_threadsPerThreadgroup(threadgroups(edge_threads), GROUP_SIZE);
321 }
322 _ => {
323 encoder.setComputePipelineState(&self.gpu.walk_accumulate);
324 unsafe { bind(encoder, &[&self.psi, &self.acc], &[as_bytes(&p)]) };
326 encoder.dispatchThreadgroups_threadsPerThreadgroup(threadgroups(entries), GROUP_SIZE);
327 }
328 })
329 }
330
331 pub fn accumulated(&self) -> Vec<f64> {
333 let acc =
335 unsafe { std::slice::from_raw_parts(self.acc.contents().as_ptr() as *const f32, self.rows) };
336 acc.iter().map(|&v| v as f64).collect()
337 }
338
339 pub fn reset_accumulated(&mut self) {
341 let acc =
343 unsafe { std::slice::from_raw_parts_mut(self.acc.contents().as_ptr() as *mut f32, self.rows) };
344 acc.fill(0.0);
345 }
346
347 pub fn steps(&mut self, n: usize) -> Result<(), GpuError> {
349 let kernels = self.gpu.kernels(self.precision);
350 let p = self.params;
351 let coin_threads = p.batch as usize * ((p.nodes as usize) << p.bits);
352 let edge_threads = p.batch as usize * ((p.edges as usize) << (p.bits - 1));
353 self.gpu.run("running the walk kernels", 2 * n, |encoder, i| {
354 if i % 2 == 0 {
355 encoder.setComputePipelineState(&kernels.walk_coin);
356 unsafe {
359 bind(encoder, &[&self.psi, &self.node_rows, &self.coin_at, &self.coins], &[as_bytes(&p)])
360 };
361 encoder.dispatchThreadgroups_threadsPerThreadgroup(threadgroups(coin_threads), GROUP_SIZE);
362 } else {
363 encoder.setComputePipelineState(&kernels.walk_edge);
364 unsafe { bind(encoder, &[&self.psi, &self.halves, &self.exchange], &[as_bytes(&p)]) };
366 encoder.dispatchThreadgroups_threadsPerThreadgroup(threadgroups(edge_threads), GROUP_SIZE);
367 }
368 })
369 }
370}