Skip to main content

caroli_gpu/
cuda.rs

1//! CUDA backend (`chebyshev.cu`, f64), compiled at run time by NVRTC. The CUDA libraries are
2//! loaded when the device is opened, so building needs no CUDA toolkit; running needs an
3//! NVIDIA driver and NVRTC.
4
5use crate::{GpuError, doubled_moments};
6use caroli_model::{SparseMatrix, c64};
7use cudarc::driver::{CudaContext, CudaFunction, CudaSlice, CudaStream, LaunchConfig, PushKernelArg};
8use std::sync::Arc;
9
10const SOURCE: &str = include_str!("chebyshev.cu");
11
12/// Threads per block (`GROUP` in the kernels).
13const GROUP: usize = 256;
14
15fn backend(context: &str, error: impl std::fmt::Debug) -> GpuError {
16    GpuError::Backend(format!("{context}: {error:?}"))
17}
18
19fn flatten(z: &[c64]) -> Vec<f64> {
20    z.iter().flat_map(|v| [v.re, v.im]).collect()
21}
22
23fn unflatten(x: &[f64]) -> Vec<c64> {
24    x.as_chunks::<2>().0.iter().map(|&[re, im]| c64::new(re, im)).collect()
25}
26
27fn config(total: usize) -> LaunchConfig {
28    LaunchConfig {
29        grid_dim: (total.div_ceil(GROUP) as u32, 1, 1),
30        block_dim: (GROUP as u32, 1, 1),
31        shared_mem_bytes: 0,
32    }
33}
34
35/// A CUDA device, its stream and the compiled kernels.
36pub struct CudaDevice {
37    context: Arc<CudaContext>,
38    stream: Arc<CudaStream>,
39    kpm_step: CudaFunction,
40    reduce_partials: CudaFunction,
41    propagate_step: CudaFunction,
42    propagate_init: CudaFunction,
43}
44
45impl CudaDevice {
46    /// Device `ordinal` with the kernels compiled.
47    pub fn new(ordinal: usize) -> Result<Self, GpuError> {
48        // cudarc panics when it cannot load a library: check first.
49        // SAFETY: this only tries to open the driver's shared library.
50        if !unsafe { cudarc::driver::sys::is_culib_present() } {
51            return Err(GpuError::Unavailable("CUDA driver library not found".into()));
52        }
53        // SAFETY: this only tries to open NVRTC's shared library.
54        if !unsafe { cudarc::nvrtc::sys::is_culib_present() } {
55            return Err(GpuError::Unavailable("NVRTC library not found".into()));
56        }
57        let context = CudaContext::new(ordinal).map_err(|e| GpuError::Unavailable(format!("{e:?}")))?;
58        let ptx = cudarc::nvrtc::compile_ptx(SOURCE).map_err(|e| backend("compiling the CUDA kernels", e))?;
59        let module = context.load_module(ptx).map_err(|e| backend("loading the CUDA kernels", e))?;
60        let function = |name: &str| module.load_function(name).map_err(|e| backend(name, e));
61        Ok(Self {
62            stream: context.default_stream(),
63            kpm_step: function("kpm_step")?,
64            reduce_partials: function("reduce_partials")?,
65            propagate_step: function("propagate_step")?,
66            propagate_init: function("propagate_init")?,
67            context,
68        })
69    }
70
71    /// The GPU's name.
72    pub fn name(&self) -> String {
73        self.context.name().unwrap_or_else(|_| "CUDA device".into())
74    }
75
76    /// Uploads a rescaled Hamiltonian `H̃` (spectrum in (−1, 1)).
77    pub fn upload(&self, h: &SparseMatrix) -> Result<CudaOperator<'_>, GpuError> {
78        let row_ptr = h
79            .row_ptr
80            .iter()
81            .map(|&x| {
82                u32::try_from(x).map_err(|_| GpuError::Backend("matrix too large for u32 indices".into()))
83            })
84            .collect::<Result<Vec<u32>, _>>()?;
85        let s = &self.stream;
86        Ok(CudaOperator {
87            gpu: self,
88            n: h.n,
89            row_ptr: s.clone_htod(&row_ptr).map_err(|e| backend("upload", e))?,
90            cols: s.clone_htod(&h.cols).map_err(|e| backend("upload", e))?,
91            vals: s.clone_htod(&flatten(&h.vals)).map_err(|e| backend("upload", e))?,
92        })
93    }
94}
95
96/// A sparse Hamiltonian resident on a CUDA device.
97pub struct CudaOperator<'a> {
98    gpu: &'a CudaDevice,
99    n: usize,
100    row_ptr: CudaSlice<u32>,
101    cols: CudaSlice<u32>,
102    vals: CudaSlice<f64>,
103}
104
105impl CudaOperator<'_> {
106    fn zeros(&self, entries: usize) -> Result<CudaSlice<f64>, GpuError> {
107        self.gpu.stream.alloc_zeros::<f64>(2 * entries.max(1)).map_err(|e| backend("allocation", e))
108    }
109
110    /// KPM moments `μ_n = kernel_n · mean_r ⟨r| T_n(H̃) |r⟩` for a block of start vectors, with
111    /// the doubling relations (as `caroli_kpm::block_moments`).
112    pub fn kpm_moments(&self, starts: &[Vec<c64>], kernel: &[f64]) -> Result<Vec<c64>, GpuError> {
113        let (n, vectors) = (self.n, starts.len());
114        assert!(vectors > 0, "no start vectors");
115        assert!(starts.iter().all(|s| s.len() == n), "start vectors must have {n} entries");
116        assert!(kernel.len() >= 2, "at least two moments");
117        let total = n * vectors;
118        let total32 = u32::try_from(total).map_err(|_| GpuError::Backend("too many entries".into()))?;
119        let block: Vec<c64> = (0..total).map(|i| starts[i % vectors][i / vectors]).collect();
120        let s = &self.gpu.stream;
121        let mut prev = self.zeros(total)?;
122        let mut cur = s.clone_htod(&flatten(&block)).map_err(|e| backend("upload", e))?;
123        let mut next = self.zeros(total)?;
124        let groups = total.div_ceil(GROUP);
125        let steps = kernel.len().div_ceil(2);
126        // Per-block shares of the current step, then the reduced sums of every step.
127        let mut partials = self.zeros(2 * groups)?;
128        let mut sums = self.zeros(2 * steps)?;
129        let (vectors32, groups32) = (vectors as u32, groups as u32);
130        for step in 0..steps {
131            let (first, slot) = ((step == 0) as u32, step as u32);
132            let mut b = s.launch_builder(&self.gpu.kpm_step);
133            b.arg(&self.row_ptr).arg(&self.cols).arg(&self.vals).arg(&prev).arg(&cur).arg(&mut next);
134            b.arg(&mut partials).arg(&vectors32).arg(&total32).arg(&first);
135            // SAFETY: the arguments match `kpm_step`; indices stay below `total` and `2 groups`.
136            unsafe { b.launch(config(total)) }.map_err(|e| backend("kpm_step", e))?;
137            let mut r = s.launch_builder(&self.gpu.reduce_partials);
138            r.arg(&partials).arg(&mut sums).arg(&groups32).arg(&slot);
139            // SAFETY: the arguments match `reduce_partials`; one block.
140            unsafe { r.launch(config(1)) }.map_err(|e| backend("reduce_partials", e))?;
141            // (prev, cur, next) ← (T_n, T_{n+1}, free).
142            std::mem::swap(&mut prev, &mut cur);
143            std::mem::swap(&mut cur, &mut next);
144        }
145        let all = unflatten(&s.clone_dtoh(&sums).map_err(|e| backend("download", e))?);
146        let s1: Vec<c64> = all.iter().step_by(2).take(steps).copied().collect();
147        let s2: Vec<c64> = all.iter().skip(1).step_by(2).take(steps).copied().collect();
148        Ok(doubled_moments(&s1, &s2, vectors, kernel))
149    }
150
151    /// `steps` propagation steps `ψ ← Σ_n c_n T_n(H̃) ψ` for a block of `vectors` wave
152    /// functions stored interleaved (`ψ[row·vectors + v]`).
153    pub fn propagate(
154        &self,
155        coefficients: &[c64],
156        psi: &mut [c64],
157        vectors: usize,
158        steps: usize,
159    ) -> Result<(), GpuError> {
160        let n = self.n;
161        assert!(
162            vectors > 0 && psi.len() == n * vectors,
163            "ψ must hold {vectors} wave functions of {n} entries"
164        );
165        assert!(coefficients.len() >= 2, "at least two coefficients");
166        let total = psi.len();
167        let total32 = u32::try_from(total).map_err(|_| GpuError::Backend("too many entries".into()))?;
168        let vectors32 = vectors as u32;
169        let s = &self.gpu.stream;
170        // `cur` holds T_0 = ψ at the start of each step; `acc` accumulates Σ c_k T_k.
171        let mut cur = s.clone_htod(&flatten(psi)).map_err(|e| backend("upload", e))?;
172        let (mut prev, mut next, mut acc) = (self.zeros(total)?, self.zeros(total)?, self.zeros(total)?);
173        for _ in 0..steps {
174            let c0 = coefficients[0];
175            let mut l = s.launch_builder(&self.gpu.propagate_init);
176            l.arg(&cur).arg(&mut acc).arg(&c0.re).arg(&c0.im).arg(&total32);
177            // SAFETY: the arguments match `propagate_init`.
178            unsafe { l.launch(config(total)) }.map_err(|e| backend("propagate_init", e))?;
179            for (k, c) in coefficients.iter().enumerate().skip(1) {
180                let first = (k == 1) as u32;
181                let mut l = s.launch_builder(&self.gpu.propagate_step);
182                l.arg(&self.row_ptr).arg(&self.cols).arg(&self.vals).arg(&prev).arg(&cur).arg(&mut next);
183                l.arg(&mut acc).arg(&c.re).arg(&c.im).arg(&vectors32).arg(&total32).arg(&first);
184                // SAFETY: the arguments match `propagate_step`.
185                unsafe { l.launch(config(total)) }.map_err(|e| backend("propagate_step", e))?;
186                // (prev, cur, next) ← (T_{k−1}, T_k, free).
187                std::mem::swap(&mut prev, &mut cur);
188                std::mem::swap(&mut cur, &mut next);
189            }
190            // ψ(t + dt) is T_0 of the next step.
191            std::mem::swap(&mut cur, &mut acc);
192        }
193        let out = unflatten(&s.clone_dtoh(&cur).map_err(|e| backend("download", e))?);
194        psi.copy_from_slice(&out[..total]);
195        Ok(())
196    }
197}