Skip to main content

caroli_kpm/
accelerated.rs

1//! Kernel-polynomial moments on the GPU, checked against the CPU.
2//!
3//! The GPU computes the moments of every start vector; the CPU recomputes those of a sample
4//! (one vector in fifty, at least one) in f64, and the GPU those of the same sample. If the two
5//! differ by more than the tolerance (relative to `μ_0`), or the GPU fails, the CPU computes
6//! everything. With a single start vector the check costs a full CPU run: for a local density of
7//! states, batch the sites as start vectors.
8
9use crate::block_moments;
10use caroli_gpu::{Device, Options, Report};
11use caroli_model::{SparseMatrix, c64};
12
13/// The checked start vectors: one in fifty, evenly spaced, at least one.
14#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
15fn sample(vectors: usize) -> Vec<usize> {
16    let count = vectors.div_ceil(50);
17    (0..count).map(|k| k * vectors / count).collect()
18}
19
20/// The larger of `a` and `b`, or NaN if either is: a NaN must fail the checks, and `f64::max`
21/// would hide it (it returns the other number).
22#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
23fn max_or_nan(a: f64, b: f64) -> f64 {
24    if a.is_nan() || b.is_nan() { f64::NAN } else { a.max(b) }
25}
26
27/// `max_n |a_n − b_n| / |b_0|`, NaN if any entry is.
28#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
29fn deviation(a: &[c64], b: &[c64]) -> f64 {
30    a.iter().zip(b).map(|(x, y)| (x - y).norm()).fold(0.0, max_or_nan) / b[0].norm()
31}
32
33/// Moments `μ_n = kernel_n · mean_v ⟨r_v| T_n(H̃) |r_v⟩` of the rescaled Hamiltonian `h` (as
34/// [`block_moments`]), on the device of `options`.
35pub fn moments(
36    h: &SparseMatrix,
37    starts: &[Vec<c64>],
38    kernel: &[f64],
39    options: &Options,
40) -> (Vec<c64>, Report) {
41    let cpu = |starts: &[Vec<c64>]| block_moments(|x, y| h.apply_block(x, y, starts.len()), starts, kernel);
42    let on_cpu = |fallback: Option<String>, deviation: Option<f64>| {
43        (cpu(starts), Report { ran_on: "CPU".into(), deviation, fallback })
44    };
45    let precision = match options.device {
46        Device::Cpu => return on_cpu(None, None),
47        Device::Gpu(p) => p,
48    };
49    #[cfg(target_os = "macos")]
50    {
51        let gpu = match caroli_gpu::MetalDevice::new() {
52            Ok(g) => g,
53            Err(e) => return on_cpu(Some(format!("no GPU: {e}")), None),
54        };
55        let run = || -> Result<(Vec<c64>, f64), caroli_gpu::GpuError> {
56            let op = gpu.upload(h, precision)?;
57            let mu = op.kpm_moments(starts, kernel)?;
58            let picked: Vec<Vec<c64>> = sample(starts.len()).into_iter().map(|i| starts[i].clone()).collect();
59            let reference = cpu(&picked);
60            let checked = op.kpm_moments(&picked, kernel)?;
61            Ok((mu, deviation(&checked, &reference)))
62        };
63        match run() {
64            Err(e) => on_cpu(Some(format!("GPU: {e}")), None),
65            Ok((mu, dev)) if dev.is_nan() || dev > options.tolerance || mu.iter().any(|m| m.is_nan()) => {
66                on_cpu(
67                    Some(format!("deviation {dev:.1e} above the tolerance {:.1e}", options.tolerance)),
68                    Some(dev),
69                )
70            }
71            Ok((mu, dev)) => (
72                mu,
73                Report {
74                    ran_on: format!("{} ({precision:?})", gpu.name()),
75                    deviation: Some(dev),
76                    fallback: None,
77                },
78            ),
79        }
80    }
81    #[cfg(not(target_os = "macos"))]
82    {
83        let _ = precision;
84        on_cpu(Some("no GPU backend for the KPM on this platform (Metal only)".into()), None)
85    }
86}
87
88#[cfg(test)]
89mod tests {
90    use super::*;
91    use crate::{jackson, random_phases};
92    use caroli_disorder::rng::Xoshiro256;
93    use caroli_gpu::Precision;
94
95    /// A ring with random on-site energies, rescaled into (−1, 1).
96    fn ring(n: usize) -> SparseMatrix {
97        let mut rng = Xoshiro256::seed_from_u64(3);
98        let mut entries = Vec::new();
99        for i in 0..n {
100            entries.push((i, i, c64::new(0.5 * (2.0 * rng.uniform() - 1.0), 0.0)));
101            entries.push((i, (i + 1) % n, c64::new(-0.6, 0.0)));
102            entries.push(((i + 1) % n, i, c64::new(-0.6, 0.0)));
103        }
104        SparseMatrix::from_triplets(n, entries).rescaled(0.0, 1.8)
105    }
106
107    #[test]
108    fn checked_moments() {
109        let h = ring(4096);
110        let mut rng = Xoshiro256::seed_from_u64(9);
111        let starts: Vec<Vec<c64>> = (0..60).map(|_| random_phases(&mut rng, h.n)).collect();
112        let kernel = jackson(256);
113        let (exact, report) = moments(&h, &starts, &kernel, &Options::cpu());
114        assert_eq!(report.ran_on, "CPU");
115        // double-single: on the GPU when there is one, within 1e-10 of the CPU.
116        let (mu, report) = moments(&h, &starts, &kernel, &Options::accurate());
117        assert!(deviation(&mu, &exact) < 1e-10, "{report:?}");
118        if report.fallback.is_some() {
119            return; // no GPU here
120        }
121        assert!(report.deviation.unwrap() < 1e-10);
122        // f32 within 1e-3; an impossible tolerance sends it back to the CPU, which is exact.
123        let (mu, report) = moments(&h, &starts, &kernel, &Options::exploration());
124        assert!(report.fallback.is_none() && deviation(&mu, &exact) < 1e-4, "{report:?}");
125        let strict = Options { device: Device::Gpu(Precision::Single), tolerance: 1e-12 };
126        let (mu, report) = moments(&h, &starts, &kernel, &strict);
127        assert_eq!(report.ran_on, "CPU");
128        assert!(report.fallback.is_some() && report.deviation.unwrap() > 1e-12);
129        assert_eq!(mu, exact);
130        assert_eq!(sample(60), vec![0, 30]);
131        assert_eq!(sample(1), vec![0]);
132    }
133}