caroli_gpu/lib.rs
1//! GPU backends for the Chebyshev kernels of caroli: kernel-polynomial moments and time
2//! propagation with a sparse Hamiltonian ([`caroli_model::SparseMatrix`]) rescaled so that its
3//! spectrum lies in (−1, 1).
4//!
5//! The work is a chain of fused steps `T_{n+1} = 2 H̃ T_n − T_{n−1}`. Each step reduces
6//! `⟨r|T_{n+1}⟩` (KPM) or accumulates `c_{n+1} T_{n+1}` (propagation) as it goes, so a whole
7//! expansion runs on the GPU and only the moments or the final state come back. Several vectors
8//! go through each step together (stochastic traces, several wave packets).
9//!
10//! - **Metal** (macOS). Apple GPUs have no f64:
11//! - [`Precision::Single`] runs in f32, about 1e-6 relative;
12//! - [`Precision::DoubleSingle`] stores and computes every number as an unevaluated sum of two
13//! f32, about 1e-14 relative, for twice the memory traffic of f32.
14//! - **CUDA** (feature `cuda`): f64.
15
16// docs.rs (`--cfg docsrs`, nightly) marks the items that exist only on macOS or with `cuda`.
17#![cfg_attr(docsrs, feature(doc_cfg))]
18
19use caroli_model::c64;
20
21// The calls into Metal (Objective-C, through objc2) and into CUDA's driver are unsafe by nature:
22// these three modules are the crate's only unsafe code, every block with its `SAFETY` reason.
23#[cfg(target_os = "macos")]
24#[allow(unsafe_code)]
25pub mod metal;
26
27#[cfg(target_os = "macos")]
28#[allow(unsafe_code)]
29mod metal_walk;
30
31#[cfg(target_os = "macos")]
32pub use metal::{MetalDevice, MetalOperator};
33
34#[cfg(target_os = "macos")]
35pub use metal_walk::{MAX_DEGREE, MetalWalk, WalkTables};
36
37#[cfg(feature = "cuda")]
38#[allow(unsafe_code)]
39pub mod cuda;
40
41#[cfg(feature = "cuda")]
42pub use cuda::{CudaDevice, CudaOperator};
43
44/// Floating-point format of a Metal computation.
45#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46pub enum Precision {
47 /// f32.
48 Single,
49 /// Double-single: `hi + lo` with two f32 (48-bit significand).
50 DoubleSingle,
51}
52
53/// Error of a GPU computation.
54#[derive(thiserror::Error, Debug)]
55pub enum GpuError {
56 /// No GPU to run on, and why: no Metal device, no CUDA driver or NVRTC library, or no such
57 /// CUDA device.
58 #[error("no GPU: {0}")]
59 Unavailable(String),
60 /// The GPU could not do the work, and why: kernels that fail to compile or load, an allocation
61 /// or a launch that fails, sizes beyond the kernels' 32-bit indices, inputs they do not take.
62 #[error("GPU: {0}")]
63 Backend(String),
64}
65
66/// `μ_n = kernel_n · mean_r ⟨r| T_n |r⟩` from the block sums `s1[n] = Σ_r ⟨T_n|T_n⟩` and
67/// `s2[n] = Σ_r ⟨T_n|T_{n+1}⟩` (`μ_2n = 2 s1[n] − μ_0`, `μ_{2n+1} = 2 s2[n] − μ_1`).
68#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
69pub(crate) fn doubled_moments(s1: &[c64], s2: &[c64], vectors: usize, kernel: &[f64]) -> Vec<c64> {
70 let (mu0, mu1) = (s1[0], s2[0]);
71 (0..kernel.len())
72 .map(|k| {
73 let raw = match k {
74 0 => mu0,
75 1 => mu1,
76 _ if k % 2 == 0 => 2.0 * s1[k / 2] - mu0,
77 _ => 2.0 * s2[k / 2] - mu1,
78 };
79 raw * (kernel[k] / vectors as f64)
80 })
81 .collect()
82}
83
84/// Where a computation runs.
85#[derive(Clone, Copy, Debug, PartialEq, Eq)]
86pub enum Device {
87 /// f64 on the CPU.
88 Cpu,
89 /// On the GPU (Metal) in this precision, checked against the CPU.
90 Gpu(Precision),
91}
92
93/// Where a checked computation runs, and the error it may take before the CPU takes over.
94#[derive(Clone, Copy, Debug, PartialEq)]
95pub struct Options {
96 /// Where it runs: the CPU in f64, or the GPU in a precision.
97 pub device: Device,
98 /// Largest relative error accepted, as measured against the CPU on a sample of the work.
99 pub tolerance: f64,
100}
101
102impl Options {
103 /// f64 on the CPU.
104 pub fn cpu() -> Self {
105 Self { device: Device::Cpu, tolerance: 0.0 }
106 }
107
108 /// Fast exploration: the GPU in f32, relative errors up to 10⁻³ accepted.
109 pub fn exploration() -> Self {
110 Self { device: Device::Gpu(Precision::Single), tolerance: 1e-3 }
111 }
112
113 /// The GPU in double-single, relative errors up to 10⁻⁹ accepted.
114 pub fn accurate() -> Self {
115 Self { device: Device::Gpu(Precision::DoubleSingle), tolerance: 1e-9 }
116 }
117}
118
119/// What a checked computation did.
120#[derive(Clone, Debug, Default, PartialEq)]
121pub struct Report {
122 /// "CPU", or the GPU and its precision.
123 pub ran_on: String,
124 /// Relative deviation from the CPU measured on the checked sample (scaled to the whole
125 /// computation where it grows with it).
126 pub deviation: Option<f64>,
127 /// Why the CPU took over.
128 pub fallback: Option<String>,
129}