Skip to main content

caroli_walk/
gpu.rs

1//! Running a walk on the GPU in reduced precision, checked against the CPU, which takes over
2//! when the error would exceed the tolerance.
3//!
4//! - **Calibration.** The first 2 % of the steps (at least one, at most 200) run on the CPU in
5//!   f64 and on the GPU from the same state; the distance between the two states, scaled
6//!   linearly to the whole run, predicts the final error. Above the tolerance, f32 gives way to
7//!   double-single, then to the CPU.
8//! - **Checks.** At every checkpoint the CPU sums `‖ψ‖²` in f64; a drift above the tolerance
9//!   (or a NaN) sends the run back to the CPU from the last good checkpoint.
10//! - **Report.** Every run says where it ran, the calibrated error and the norm drift.
11
12use crate::walk::SpinWalk;
13use caroli_gpu::Precision;
14use caroli_model::c64;
15
16/// Where a walk runs.
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub enum Device {
19    /// f64 on the CPU.
20    Cpu,
21    /// On the GPU in this precision (Metal), checked against the CPU.
22    Gpu(Precision),
23}
24
25/// How a walk runs.
26#[derive(Clone, Copy, Debug, PartialEq)]
27pub struct Options {
28    /// Where the walk runs: the CPU in f64, or the GPU in a precision.
29    pub device: Device,
30    /// Largest error `‖ψ − ψ_exact‖` (of a normalized state) accepted at the end.
31    pub tolerance: f64,
32    /// Steps between checkpoints (observations and checks); 0 for the start and the end only.
33    pub every: usize,
34}
35
36impl Options {
37    /// f64 on the CPU.
38    pub fn cpu(every: usize) -> Self {
39        Self { device: Device::Cpu, tolerance: 0.0, every }
40    }
41
42    /// Exploration: the GPU in f32, errors up to 10⁻³ accepted.
43    pub fn exploration(every: usize) -> Self {
44        Self { device: Device::Gpu(Precision::Single), tolerance: 1e-3, every }
45    }
46
47    /// The GPU in double-single, errors up to 10⁻⁹ accepted.
48    pub fn accurate(every: usize) -> Self {
49        Self { device: Device::Gpu(Precision::DoubleSingle), tolerance: 1e-9, every }
50    }
51}
52
53/// What a run did.
54#[derive(Clone, Debug, Default, PartialEq)]
55pub struct Report {
56    /// "CPU", or the GPU and the precision of its last steps.
57    pub ran_on: String,
58    /// Steps of each calibration and the measured distance between GPU and CPU after them.
59    pub calibrations: Vec<(Precision, usize, f64)>,
60    /// Error predicted at the last step by the accepted calibration.
61    pub predicted_error: Option<f64>,
62    /// Largest relative drift of `‖ψ‖²` seen at the GPU checkpoints.
63    pub norm_drift: f64,
64    /// Step from which the CPU took over, and why.
65    pub fallback: Option<(usize, String)>,
66    /// Steps run on the GPU after an accepted calibration; a segment refused at its checkpoint
67    /// counts too, and the CPU redoes it.
68    pub gpu_steps: usize,
69    /// Steps run on the CPU in f64: the calibrations (also run on the GPU) and every step after a
70    /// fallback.
71    pub cpu_steps: usize,
72}
73
74/// The tables of a walk for the GPU kernels.
75#[cfg(target_os = "macos")]
76pub(crate) struct Tables {
77    bits: usize,
78    node_rows: Vec<usize>,
79    coins: Vec<Vec<c64>>,
80    halves: Vec<(usize, usize)>,
81    exchange: [c64; 3],
82}
83
84#[cfg(target_os = "macos")]
85impl Tables {
86    pub(crate) fn of(walk: &SpinWalk) -> Self {
87        let graph = walk.graph();
88        let (p, alpha, beta) = walk.exchange();
89        Self {
90            bits: graph.edges(),
91            node_rows: (0..graph.nodes())
92                .map(|x| graph.half_edges_of(x).start)
93                .chain([graph.half_edges()])
94                .collect(),
95            coins: walk
96                .coins()
97                .iter()
98                .map(|c| (0..c.nrows()).flat_map(|i| (0..c.ncols()).map(move |j| c[(i, j)])).collect())
99                .collect(),
100            halves: (0..graph.edges()).map(|e| graph.halves(e)).collect(),
101            exchange: [p, alpha, beta],
102        }
103    }
104
105    pub(crate) fn view(&self) -> caroli_gpu::WalkTables<'_> {
106        caroli_gpu::WalkTables {
107            bits: self.bits,
108            node_rows: &self.node_rows,
109            coins: &self.coins,
110            halves: &self.halves,
111            exchange: self.exchange,
112        }
113    }
114}
115
116/// Steps per calibration: 2 % of the run, at least one, at most 200.
117#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
118fn calibration_steps(steps: usize) -> usize {
119    (steps / 50).clamp(1, 200)
120}
121
122/// Runs `steps` steps from `psi` (left at the last step) and calls `observe(t, ψ)` at `t = 0`,
123/// every `options.every` steps and at the end.
124pub fn evolve(
125    walk: &SpinWalk,
126    psi: &mut [c64],
127    steps: usize,
128    options: &Options,
129    mut observe: impl FnMut(usize, &[c64]),
130) -> Report {
131    let every = if options.every == 0 { steps.max(1) } else { options.every };
132    let mut report = Report::default();
133    observe(0, psi);
134    let mut t = 0;
135    if let Device::Gpu(precision) = options.device {
136        t = run_gpu(walk, psi, steps, every, precision, options.tolerance, &mut observe, &mut report);
137    }
138    if t < steps {
139        report.ran_on =
140            if report.ran_on.is_empty() { "CPU".into() } else { format!("{}, then the CPU", report.ran_on) };
141        cpu_segment(walk, psi, t, steps, steps, every, &mut observe);
142        report.cpu_steps += steps - t;
143    } else if report.ran_on.is_empty() {
144        report.ran_on = "CPU".into();
145    }
146    report
147}
148
149/// CPU steps from `t` to `end`, observing at the checkpoints of a run that ends at `last`.
150fn cpu_segment(
151    walk: &SpinWalk,
152    psi: &mut [c64],
153    mut t: usize,
154    end: usize,
155    last: usize,
156    every: usize,
157    observe: &mut impl FnMut(usize, &[c64]),
158) {
159    while t < end {
160        let next = next_checkpoint(t, last, every).min(end);
161        walk.steps(psi, next - t);
162        t = next;
163        if t.is_multiple_of(every) || t == last {
164            observe(t, psi);
165        }
166    }
167}
168
169/// The checkpoint after `t`: the next multiple of `every`, or the end.
170fn next_checkpoint(t: usize, end: usize, every: usize) -> usize {
171    ((t / every + 1) * every).min(end)
172}
173
174/// The GPU part of [`evolve`]: returns the step reached; the CPU does the rest.
175#[cfg(target_os = "macos")]
176#[allow(clippy::too_many_arguments)]
177fn run_gpu(
178    walk: &SpinWalk,
179    psi: &mut [c64],
180    steps: usize,
181    every: usize,
182    precision: Precision,
183    tolerance: f64,
184    observe: &mut impl FnMut(usize, &[c64]),
185    report: &mut Report,
186) -> usize {
187    use caroli_gpu::MetalDevice;
188    let gpu = match MetalDevice::new() {
189        Ok(g) => g,
190        Err(e) => {
191            report.fallback = Some((0, format!("no GPU: {e}")));
192            return 0;
193        }
194    };
195    let owned = Tables::of(walk);
196    let tables = owned.view();
197    let norm0: f64 = psi.iter().map(|z| z.norm_sqr()).sum();
198    let candidates: &[Precision] = match precision {
199        Precision::Single => &[Precision::Single, Precision::DoubleSingle],
200        Precision::DoubleSingle => &[Precision::DoubleSingle],
201    };
202    let mut t = 0;
203    for &candidate in candidates {
204        if t >= steps {
205            break;
206        }
207        let mut device = match gpu.walk(&tables, psi, candidate) {
208            Ok(w) => w,
209            Err(e) => {
210                report.fallback = Some((t, format!("GPU: {e}")));
211                return t;
212            }
213        };
214        // Calibration: the same steps on both, from the same state.
215        let k = calibration_steps(steps).min(steps - t);
216        let start = t;
217        cpu_segment(walk, psi, start, start + k, steps, every, observe);
218        report.cpu_steps += k;
219        t = start + k;
220        if let Err(e) = device.steps(k) {
221            report.fallback = Some((t, format!("GPU: {e}")));
222            return t;
223        }
224        let error = device.distance(psi) / norm0.sqrt();
225        report.calibrations.push((candidate, k, error));
226        let predicted = error * steps as f64 / k as f64;
227        if predicted.is_nan() || predicted > tolerance {
228            report.fallback = Some((
229                t,
230                format!("{candidate:?}: predicted error {predicted:.1e} above the tolerance {tolerance:.1e}"),
231            ));
232            continue;
233        }
234        report.fallback = None;
235        report.predicted_error = Some(predicted);
236        report.ran_on = format!("{} ({candidate:?})", gpu.name());
237        // Accepted: continue on the GPU from the exact state.
238        device.set_state(psi);
239        while t < steps {
240            let next = next_checkpoint(t, steps, every);
241            if let Err(e) = device.steps(next - t) {
242                report.fallback = Some((t, format!("GPU: {e}")));
243                return t;
244            }
245            report.gpu_steps += next - t;
246            let drift = (device.norm_sqr() - norm0).abs() / norm0;
247            report.norm_drift = report.norm_drift.max(if drift.is_nan() { f64::INFINITY } else { drift });
248            if drift.is_nan() || drift > tolerance {
249                report.fallback =
250                    Some((t, format!("norm drift {drift:.1e} above the tolerance {tolerance:.1e}")));
251                return t;
252            }
253            device.read_into(psi);
254            t = next;
255            observe(t, psi);
256        }
257        return t;
258    }
259    t
260}
261
262#[cfg(not(target_os = "macos"))]
263#[allow(clippy::too_many_arguments)]
264fn run_gpu(
265    _walk: &SpinWalk,
266    _psi: &mut [c64],
267    _steps: usize,
268    _every: usize,
269    _precision: Precision,
270    _tolerance: f64,
271    _observe: &mut impl FnMut(usize, &[c64]),
272    report: &mut Report,
273) -> usize {
274    report.fallback = Some((0, "no GPU walk backend on this platform (Metal only)".into()));
275    0
276}
277
278#[cfg(test)]
279mod tests {
280    use super::*;
281    use crate::walk::PLUS;
282
283    fn run(options: &Options, steps: usize) -> (Vec<c64>, Vec<(usize, f64)>, Report) {
284        let walk = SpinWalk::ring(6, 0.5, 0.7);
285        let mut psi = walk.product_state(&walk.localized(0, 0), &[PLUS; 6]);
286        let mut seen = Vec::new();
287        let report = evolve(&walk, &mut psi, steps, options, |t, psi| {
288            seen.push((t, walk.node_probabilities(psi)[0]));
289        });
290        (psi, seen, report)
291    }
292
293    #[test]
294    fn cpu_checkpoints() {
295        let (_, seen, report) = run(&Options::cpu(40), 100);
296        assert_eq!(seen.iter().map(|s| s.0).collect::<Vec<_>>(), vec![0, 40, 80, 100]);
297        assert_eq!((report.ran_on.as_str(), report.cpu_steps, report.gpu_steps), ("CPU", 100, 0));
298    }
299
300    /// On a Mac with a GPU: double-single agrees with the CPU to ~1e-12 and stays on the GPU;
301    /// an impossible tolerance sends f32 and double-single back to the CPU, which then gives the
302    /// exact result.
303    #[test]
304    fn gpu_checked_against_cpu() {
305        let (exact, cpu_seen, _) = run(&Options::cpu(40), 300);
306        let (psi, seen, report) = run(&Options::accurate(40), 300);
307        let distance =
308            |a: &[c64], b: &[c64]| a.iter().zip(b).map(|(x, y)| (x - y).norm_sqr()).sum::<f64>().sqrt();
309        assert_eq!(seen.len(), cpu_seen.len());
310        if report.gpu_steps == 0 {
311            // No GPU here: the CPU ran everything.
312            assert!(report.fallback.is_some() && distance(&psi, &exact) < 1e-14);
313            return;
314        }
315        assert!(report.fallback.is_none(), "{report:?}");
316        assert!(distance(&psi, &exact) < 1e-10, "double-single: {}", distance(&psi, &exact));
317        assert!(report.norm_drift < 1e-10);
318        let strict = Options { device: Device::Gpu(Precision::Single), tolerance: 1e-15, every: 40 };
319        let (psi, seen, report) = run(&strict, 300);
320        assert_eq!(report.ran_on, "CPU");
321        assert_eq!(report.calibrations.len(), 2);
322        assert!(report.calibrations[0].2 > 1e-9 && report.calibrations[1].2 < 1e-10);
323        assert!(distance(&psi, &exact) < 1e-14);
324        assert_eq!(
325            seen.iter().map(|s| s.0).collect::<Vec<_>>(),
326            cpu_seen.iter().map(|s| s.0).collect::<Vec<_>>()
327        );
328        // f32 with an exploration tolerance stays on the GPU.
329        let (psi, _, report) = run(&Options::exploration(40), 300);
330        assert!(report.fallback.is_none() && report.ran_on.contains("Single"), "{report:?}");
331        assert!(distance(&psi, &exact) < 1e-4, "f32: {}", distance(&psi, &exact));
332    }
333}