Skip to main content

caroli_dynamics/
accelerated.rs

1//! Chebyshev propagation on the GPU, checked against the CPU.
2//!
3//! - **Calibration.** The first 2 % of the steps (at least one, at most 50) run on the CPU in
4//!   f64 and on the GPU from the same state. Their distance, relative to `‖ψ‖` and scaled
5//!   linearly to the whole run, predicts the final error; above the tolerance the CPU does the
6//!   rest. Otherwise the GPU continues from the CPU state.
7//! - **Final check.** The norm of every wave function must stay within the tolerance; if it does
8//!   not (or the GPU fails), the CPU recomputes the whole run.
9
10use crate::Chebyshev;
11use caroli_gpu::{Device, Options, Report};
12use caroli_model::{SparseMatrix, c64};
13
14/// The larger of `a` and `b`, or NaN if either is: a NaN must fail the checks, and `f64::max`
15/// would hide it (it returns the other number).
16#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
17fn max_or_nan(a: f64, b: f64) -> f64 {
18    if a.is_nan() || b.is_nan() { f64::NAN } else { a.max(b) }
19}
20
21#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
22fn norms(psi: &[c64], vectors: usize) -> Vec<f64> {
23    let mut n = vec![0.0; vectors];
24    for (i, z) in psi.iter().enumerate() {
25        n[i % vectors] += z.norm_sqr();
26    }
27    n
28}
29
30/// `steps` steps `ψ ← exp(−iH dt) ψ` of the propagator `cheb` with the rescaled Hamiltonian `h`,
31/// for a block of `vectors` wave functions stored interleaved (as `SparseMatrix::apply_block`),
32/// on the device of `options`.
33pub fn propagate(
34    h: &SparseMatrix,
35    cheb: &Chebyshev,
36    psi: &mut [c64],
37    vectors: usize,
38    steps: usize,
39    options: &Options,
40) -> Report {
41    assert!(
42        vectors > 0 && psi.len() == h.n * vectors,
43        "ψ must hold {vectors} wave functions of {} entries",
44        h.n
45    );
46    let cpu = |psi: &mut [c64], steps: usize| {
47        for _ in 0..steps {
48            cheb.step(|x, y| h.apply_block(x, y, vectors), psi);
49        }
50    };
51    let precision = match options.device {
52        Device::Cpu => {
53            cpu(psi, steps);
54            return Report { ran_on: "CPU".into(), ..Report::default() };
55        }
56        Device::Gpu(p) => p,
57    };
58    #[cfg(target_os = "macos")]
59    {
60        let start = psi.to_vec();
61        let before = norms(psi, vectors);
62        let mut report = Report::default();
63        let gpu = match caroli_gpu::MetalDevice::new() {
64            Ok(g) => g,
65            Err(e) => {
66                cpu(psi, steps);
67                return Report {
68                    ran_on: "CPU".into(),
69                    deviation: None,
70                    fallback: Some(format!("no GPU: {e}")),
71                };
72            }
73        };
74        let k = (steps / 50).clamp(1, 50).min(steps);
75        let run = |psi: &mut [c64], report: &mut Report| -> Result<bool, caroli_gpu::GpuError> {
76            let op = gpu.upload(h, precision)?;
77            let mut on_gpu = psi.to_vec();
78            op.propagate(&cheb.coefficients, &mut on_gpu, vectors, k)?;
79            cpu(psi, k);
80            let scale: f64 = psi.iter().map(|z| z.norm_sqr()).sum::<f64>().sqrt();
81            let distance = on_gpu.iter().zip(psi.iter()).map(|(a, b)| (a - b).norm_sqr()).sum::<f64>().sqrt();
82            let predicted = distance / scale * steps as f64 / k as f64;
83            report.deviation = Some(predicted);
84            if predicted.is_nan() || predicted > options.tolerance {
85                report.fallback = Some(format!(
86                    "predicted error {predicted:.1e} above the tolerance {:.1e}",
87                    options.tolerance
88                ));
89                cpu(psi, steps - k);
90                return Ok(false);
91            }
92            op.propagate(&cheb.coefficients, psi, vectors, steps - k)?;
93            Ok(true)
94        };
95        match run(psi, &mut report) {
96            Ok(false) => report.ran_on = "CPU".into(),
97            Ok(true) => {
98                let drift = norms(psi, vectors)
99                    .iter()
100                    .zip(&before)
101                    .map(|(a, b)| (a - b).abs() / b)
102                    .fold(0.0, max_or_nan);
103                if drift.is_nan() || drift > options.tolerance {
104                    psi.copy_from_slice(&start);
105                    cpu(psi, steps);
106                    report.ran_on = "CPU".into();
107                    report.fallback =
108                        Some(format!("norm drift {drift:.1e} above the tolerance {:.1e}", options.tolerance));
109                } else {
110                    report.ran_on = format!("{} ({precision:?})", gpu.name());
111                }
112            }
113            Err(e) => {
114                psi.copy_from_slice(&start);
115                cpu(psi, steps);
116                report =
117                    Report { ran_on: "CPU".into(), deviation: None, fallback: Some(format!("GPU: {e}")) };
118            }
119        }
120        report
121    }
122    #[cfg(not(target_os = "macos"))]
123    {
124        let _ = precision;
125        cpu(psi, steps);
126        Report {
127            ran_on: "CPU".into(),
128            deviation: None,
129            fallback: Some("no GPU backend for the propagation on this platform (Metal only)".into()),
130        }
131    }
132}
133
134#[cfg(test)]
135mod tests {
136    use super::*;
137    use caroli_gpu::Precision;
138
139    #[test]
140    fn checked_propagation() {
141        // A ring with a linear potential, rescaled into (−1, 1).
142        let n = 2048;
143        let mut entries = Vec::new();
144        for i in 0..n {
145            entries.push((i, i, c64::new(0.3 * (i as f64 / n as f64 - 0.5), 0.0)));
146            entries.push((i, (i + 1) % n, c64::new(-0.5, 0.0)));
147            entries.push(((i + 1) % n, i, c64::new(-0.5, 0.0)));
148        }
149        let h = SparseMatrix::from_triplets(n, entries);
150        let (centre, half) = (0.0, 1.2);
151        let scaled = h.rescaled(centre, half);
152        let cheb = Chebyshev::new(0.4, centre, half, 1e-15);
153        let norm = (n as f64).sqrt();
154        let psi0: Vec<c64> = (0..2 * n).map(|i| c64::from_polar(1.0 / norm, 0.01 * (i * i) as f64)).collect();
155        let steps = 100;
156        let run = |options: &Options| {
157            let mut psi = psi0.clone();
158            let report = propagate(&scaled, &cheb, &mut psi, 2, steps, options);
159            (psi, report)
160        };
161        let (exact, report) = run(&Options::cpu());
162        assert_eq!(report.ran_on, "CPU");
163        let distance = |a: &[c64]| a.iter().zip(&exact).map(|(x, y)| (x - y).norm_sqr()).sum::<f64>().sqrt();
164        let (psi, report) = run(&Options::accurate());
165        assert!(distance(&psi) < 1e-10, "{report:?}");
166        if report.fallback.is_some() {
167            return; // no GPU here
168        }
169        let (psi, report) = run(&Options::exploration());
170        assert!(report.fallback.is_none() && distance(&psi) < 1e-3, "{report:?}");
171        let strict = Options { device: Device::Gpu(Precision::Single), tolerance: 1e-12 };
172        let (psi, report) = run(&strict);
173        assert_eq!(report.ran_on, "CPU");
174        assert!(report.fallback.is_some() && distance(&psi) < 1e-13, "{report:?}");
175    }
176}