Skip to main content

gam_gpu/
mod.rs

1// GPU acceleration support.
2//
3// Infrastructure modules live at this level and are intentionally callable
4// from CPU-only builds: all public entry points are available without CUDA,
5// and the runtime reports an unavailable backend instead of changing
6// numerical results. CUDA-specific code is compiled only for Linux builds that
7// enable the `cuda` feature, so cudarc is never loaded by default CPU-only
8// builds.
9
10// `gpu_error` is declared first so its `#[macro_use]` macros (`gpu_err!`,
11// `gpu_bail!`) are in textual scope for every module below — `backend_probe`
12// in particular calls `gpu_err!` unqualified. Referring to these
13// `#[macro_export]` macros by absolute path (`crate::gpu_err`) is rejected
14// here: `lib.rs` pulls this module tree in via `include!`, which makes every
15// exported macro "macro-expanded", and absolute-path access to those is a
16// denied future-incompat lint.
17#[macro_use]
18pub mod gpu_error;
19pub mod backend_probe;
20pub mod blas;
21#[cfg(target_os = "linux")]
22pub mod calibration;
23pub mod cpu_traits;
24pub mod device;
25pub mod device_cache;
26pub mod device_runtime;
27pub mod dictionary_score;
28pub mod driver;
29pub mod encode_throughput;
30pub mod linalg_dispatch;
31pub mod memory;
32pub mod numerics_device;
33pub mod numerics_host;
34pub mod policy;
35pub mod pool;
36pub mod profile;
37pub mod solver;
38
39// Domain-specific GPU kernels are isolated from the infrastructure modules.
40pub mod kernels;
41
42pub use cpu_traits::MatrixLocation;
43pub use device::GpuDeviceInfo;
44pub use device_runtime::GpuRuntime;
45pub use dictionary_score::{
46    DEFAULT_DICTIONARY_SCORE_MIN_ELEMS, DEFAULT_DICTIONARY_SCORE_TILE_ELEMS,
47    DictionaryScoreRoutePlan,
48};
49pub use gpu_error::GpuError;
50pub use memory::{DeviceBuffer, DeviceCsrMatrix, DeviceMatrix, DeviceVector};
51pub use policy::{GpuDispatchPolicy, GpuMixedPrecisionPolicy};
52pub use pool::{balanced_partition, scatter_batched};
53pub use profile::{GpuExecutionTelemetry, KernelStat, KernelStatsSnapshot};
54
55// ---------------------------------------------------------------------------
56// User-facing policy and instrumentation hooks (formerly src/gpu.rs).
57//
58// The first production-safe step for acceleration is an explicit policy
59// layer: `Auto` may opportunistically use supported device-resident kernels,
60// `Off` guarantees the CPU path, and `Required` turns an unsupported GPU route
61// into a hard error instead of a silent CPU fallback. The numerical kernels
62// are wired to call these helpers before selecting a backend; until a vendor
63// backend is compiled in this module intentionally reports "unsupported" so
64// `required` fails loudly while `auto` remains a correct CPU fallback.
65// ---------------------------------------------------------------------------
66
67use serde::{Deserialize, Serialize};
68use std::fmt;
69use std::sync::OnceLock;
70
71#[derive(Clone, Copy, Debug, Eq, PartialEq)]
72pub enum CudaBackendStatus {
73    CudaUnavailable,
74    CudaReady,
75}
76
77#[inline]
78pub(crate) fn cuda_backend_status() -> CudaBackendStatus {
79    if device_runtime::GpuRuntime::global().is_some() {
80        CudaBackendStatus::CudaReady
81    } else {
82        CudaBackendStatus::CudaUnavailable
83    }
84}
85
86/// User-facing GPU backend policy.
87#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
88#[serde(rename_all = "kebab-case")]
89pub enum GpuPolicy {
90    /// Let the solver use GPU kernels only for supported, large-enough paths.
91    #[default]
92    Auto,
93    /// Always use CPU kernels.
94    Off,
95    /// Require GPU kernels and error if the requested path is unsupported.
96    Required,
97}
98
99impl GpuPolicy {
100    pub fn parse(raw: &str) -> Option<Self> {
101        match raw.trim().to_ascii_lowercase().as_str() {
102            "auto" => Some(Self::Auto),
103            "off" => Some(Self::Off),
104            "required" => Some(Self::Required),
105            _ => None,
106        }
107    }
108
109    #[inline]
110    pub const fn as_str(self) -> &'static str {
111        match self {
112            Self::Auto => "auto",
113            Self::Off => "off",
114            Self::Required => "required",
115        }
116    }
117}
118
119impl fmt::Display for GpuPolicy {
120    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121        f.write_str(self.as_str())
122    }
123}
124
125#[derive(Clone, Copy, Debug, Eq, PartialEq)]
126pub enum GpuKernel {
127    DenseMatvec,
128    DenseTransposeMatvec,
129    DenseXtWX,
130    CandidateScreen,
131    DenseSolve,
132    MatrixFreePcg,
133    SparseAssembly,
134    SpatialKernelOperator,
135    MarginalSlopeRows,
136    RemlTrace,
137    FinalInference,
138}
139
140impl GpuKernel {
141    pub const fn as_str(self) -> &'static str {
142        match self {
143            Self::DenseMatvec => "dense-matvec",
144            Self::DenseTransposeMatvec => "dense-transpose-matvec",
145            Self::DenseXtWX => "dense-xtwx",
146            Self::CandidateScreen => "candidate-screen",
147            Self::DenseSolve => "dense-solve",
148            Self::MatrixFreePcg => "matrix-free-pcg",
149            Self::SparseAssembly => "sparse-assembly",
150            Self::SpatialKernelOperator => "spatial-kernel-operator",
151            Self::MarginalSlopeRows => "marginal-slope-rows",
152            Self::RemlTrace => "reml-trace",
153            Self::FinalInference => "final-inference",
154        }
155    }
156}
157
158/// A backend-selection decision for a single hot kernel.
159#[derive(Clone, Debug)]
160pub struct GpuDecision {
161    pub policy: GpuPolicy,
162    pub kernel: GpuKernel,
163    pub use_gpu: bool,
164    pub reason: &'static str,
165}
166
167static POLICY: OnceLock<GpuPolicy> = OnceLock::new();
168
169#[inline]
170pub fn global_policy() -> GpuPolicy {
171    // Reading the policy must NOT claim the OnceLock slot: returning the
172    // default `Auto` via `get_or_init` would race against an explicit
173    // `configure_global_policy(...)` made later in the same process and
174    // silently lock the policy to `Auto`.  Keep the slot uninitialized
175    // until explicitly configured so first-writer-wins applies only to
176    // genuine writes, not to incidental reads from probe/dispatch code.
177    match POLICY.get() {
178        Some(p) => *p,
179        None => GpuPolicy::Auto,
180    }
181}
182
183/// Configure the process-wide policy before solver kernels are selected.
184/// If a previous explicit configuration already set the policy, the first
185/// value wins so concurrent fits cannot race policy changes.  Reads of
186/// `global_policy()` never claim the slot, so the very first explicit
187/// configuration always sticks even if dispatch code observed the
188/// default `Auto` beforehand.
189pub fn configure_global_policy(policy: GpuPolicy) {
190    // First-writer-wins semantics; ignore a redundant late call.
191    POLICY.set(policy).ok();
192}
193
194/// True when direct solver GPU entry points should be attempted.
195///
196/// `Auto` attempts CUDA only after the runtime probe finds a usable device.
197/// `Off` pins the process to CPU. `Required` attempts the GPU path so missing
198/// runtime/backend support becomes an explicit error at the callee instead of
199/// an implicit CPU route.
200#[inline]
201pub fn cuda_selected() -> bool {
202    match global_policy() {
203        GpuPolicy::Auto => device_runtime::GpuRuntime::is_available(),
204        GpuPolicy::Off => false,
205        GpuPolicy::Required => true,
206    }
207}
208
209/// Joint eligibility state for a GPU kernel at the call site.
210///
211/// Callers construct exactly one variant, which encodes both the compile-time
212/// backend presence and the runtime workload threshold check.  Replacing the
213/// former `(supported: bool, large_enough: bool)` pair removes the possibility
214/// of silently swapping the two flags at a call site: each meaningful state
215/// has exactly one constructor and the `match` inside [`decide`] is total.
216#[derive(Clone, Copy, Debug, Eq, PartialEq)]
217pub enum GpuEligibility {
218    /// Vendor backend is not compiled into this build for this kernel.
219    BackendNotCompiled,
220    /// Backend is compiled in, but the workload (n, m, ...) is below the
221    /// runtime threshold for this kernel.
222    WorkloadBelowThreshold,
223    /// Backend is compiled in and the workload is large enough; the only
224    /// remaining gates are policy and runtime probe.
225    Eligible,
226}
227
228impl GpuEligibility {
229    /// Combine the compile-time backend flag with the workload predicate into
230    /// the canonical joint state.  Use this only when you genuinely have two
231    /// independent booleans; otherwise prefer constructing a variant directly.
232    #[inline]
233    pub const fn from_flags(supported: bool, large_enough: bool) -> Self {
234        if !supported {
235            Self::BackendNotCompiled
236        } else if !large_enough {
237            Self::WorkloadBelowThreshold
238        } else {
239            Self::Eligible
240        }
241    }
242}
243
244/// Decide whether a GPU kernel may run. This is deliberately conservative:
245/// with no compiled vendor backend, `auto` returns CPU fallback and `required`
246/// returns an error at the call site through [`GpuDecision::require_supported`].
247pub fn decide(kernel: GpuKernel, eligibility: GpuEligibility) -> GpuDecision {
248    let policy = global_policy();
249    // Auto must consult the actual probed runtime, not only the
250    // compile-time eligibility.  Without this, `decide()` would claim
251    // GPU when the kernel is "compiled in" even though `GpuRuntime::global()`
252    // observed no device — silently producing CPU work via failed dispatch
253    // and hiding the cpu_reason from callers wanting to log fallback cause.
254    let runtime_available = device_runtime::GpuRuntime::is_available();
255    let (use_gpu, reason) = match (policy, eligibility) {
256        (GpuPolicy::Off, _) => (false, "cpu-gpu-policy-off"),
257        (GpuPolicy::Auto, GpuEligibility::BackendNotCompiled) => {
258            (false, "cpu-gpu-backend-not-compiled")
259        }
260        (GpuPolicy::Auto, _) if !runtime_available => (false, "cpu-gpu-runtime-unavailable"),
261        (GpuPolicy::Auto, GpuEligibility::WorkloadBelowThreshold) => {
262            (false, "cpu-workload-below-gpu-threshold")
263        }
264        (GpuPolicy::Auto, GpuEligibility::Eligible) => (true, "gpu-auto-supported"),
265        (GpuPolicy::Required, GpuEligibility::BackendNotCompiled) => {
266            (false, "cpu-gpu-required-unsupported")
267        }
268        (GpuPolicy::Required, _) if !runtime_available => {
269            (false, "cpu-gpu-required-runtime-unavailable")
270        }
271        // Under `required`, the workload-threshold gate is intentionally bypassed:
272        // the user explicitly asked for GPU regardless of size.
273        (GpuPolicy::Required, GpuEligibility::WorkloadBelowThreshold)
274        | (GpuPolicy::Required, GpuEligibility::Eligible) => (true, "gpu-required-supported"),
275    };
276    GpuDecision {
277        policy,
278        kernel,
279        use_gpu,
280        reason,
281    }
282}
283
284impl GpuDecision {
285    pub fn require_supported(&self) -> Result<(), String> {
286        if self.policy == GpuPolicy::Required && !self.use_gpu {
287            return Err(format!(
288                "gpu=required requested kernel '{}' but no supported device backend is available ({})",
289                self.kernel.as_str(),
290                self.reason
291            ));
292        }
293        Ok(())
294    }
295
296    pub fn log(self) {
297        log::debug!(
298            "[GPU backend] kernel={} policy={} selected={} reason={}",
299            self.kernel.as_str(),
300            self.policy.as_str(),
301            self.use_gpu,
302            self.reason
303        );
304    }
305}
306
307/// Emit the roadmap-visible kernels at startup/debug time without affecting
308/// numerical execution. This keeps backend coverage auditable as real device
309/// kernels are added incrementally.
310pub fn log_backend_inventory_once() {
311    static LOGGED: OnceLock<()> = OnceLock::new();
312    LOGGED.get_or_init(|| {
313        let compiled_backends = if cfg!(target_os = "linux") {
314            "cuda-dynamic"
315        } else {
316            "none"
317        };
318        log::debug!(
319            "[GPU backend] policy={} compiled_backends={} kernels=dense-matvec,dense-transpose-matvec,dense-xtwx,candidate-screen,dense-solve,matrix-free-pcg,sparse-assembly,spatial-kernel-operator,marginal-slope-rows,reml-trace,final-inference",
320            global_policy().as_str(),
321            compiled_backends
322        );
323    });
324}
325
326#[inline]
327pub fn try_fast_ab(
328    a: ndarray::ArrayView2<'_, f64>,
329    b: ndarray::ArrayView2<'_, f64>,
330) -> Option<ndarray::Array2<f64>> {
331    linalg_dispatch::try_fast_ab(a, b)
332}
333#[inline]
334pub fn try_fast_atb_on_ordinal(
335    ordinal: usize,
336    a: ndarray::ArrayView2<'_, f64>,
337    b: ndarray::ArrayView2<'_, f64>,
338) -> Option<ndarray::Array2<f64>> {
339    linalg_dispatch::try_fast_atb_on_ordinal(ordinal, a, b)
340}
341#[inline]
342pub fn try_fast_av(
343    a: ndarray::ArrayView2<'_, f64>,
344    v: ndarray::ArrayView1<'_, f64>,
345) -> Option<ndarray::Array1<f64>> {
346    linalg_dispatch::try_fast_av(a, v)
347}
348#[inline]
349pub fn try_fast_atv(
350    a: ndarray::ArrayView2<'_, f64>,
351    v: ndarray::ArrayView1<'_, f64>,
352) -> Option<ndarray::Array1<f64>> {
353    linalg_dispatch::try_fast_atv(a, v)
354}
355#[inline]
356pub fn try_fast_ab_broadcast_b_batched(
357    a: ndarray::ArrayView3<'_, f64>,
358    b: ndarray::ArrayView2<'_, f64>,
359) -> Option<ndarray::Array3<f64>> {
360    linalg_dispatch::try_fast_ab_broadcast_b_batched(a, b)
361}
362#[inline]
363pub fn try_fast_abt_strided_batched(
364    a: ndarray::ArrayView3<'_, f64>,
365    b: ndarray::ArrayView3<'_, f64>,
366) -> Option<ndarray::Array3<f64>> {
367    linalg_dispatch::try_fast_abt_strided_batched(a, b)
368}
369#[inline]
370pub fn try_cholesky_lower_inplace(a: &mut ndarray::Array2<f64>) -> Option<()> {
371    linalg_dispatch::try_cholesky_lower_inplace(a)
372}
373#[inline]
374pub fn try_cholesky_batched_lower_inplace(matrices: &mut [ndarray::Array2<f64>]) -> Option<()> {
375    linalg_dispatch::try_cholesky_batched_lower_inplace(matrices)
376}
377#[inline]
378pub fn try_solve_lower_triangular_matrix(
379    lower: ndarray::ArrayView2<'_, f64>,
380    rhs: ndarray::ArrayView2<'_, f64>,
381) -> Option<ndarray::Array2<f64>> {
382    linalg_dispatch::try_solve_lower_triangular_matrix(lower, rhs)
383}
384#[inline]
385pub fn try_solve_upper_triangular_matrix(
386    upper: ndarray::ArrayView2<'_, f64>,
387    rhs: ndarray::ArrayView2<'_, f64>,
388) -> Option<ndarray::Array2<f64>> {
389    linalg_dispatch::try_solve_upper_triangular_matrix(upper, rhs)
390}
391#[cfg(test)]
392mod policy_tests {
393    use super::*;
394
395    #[test]
396    fn parses_canonical_user_gpu_policy_values() {
397        assert_eq!(GpuPolicy::parse("auto"), Some(GpuPolicy::Auto));
398        assert_eq!(GpuPolicy::parse("off"), Some(GpuPolicy::Off));
399        assert_eq!(
400            GpuPolicy::parse("required"),
401            Some(GpuPolicy::Required)
402        );
403        assert_eq!(GpuPolicy::parse("force"), None);
404        assert_eq!(GpuPolicy::parse("cpu"), None);
405        assert_eq!(GpuPolicy::parse(""), None);
406        assert_eq!(GpuPolicy::parse("wat"), None);
407    }
408
409    #[test]
410    fn execution_path_defaults_to_cpu() {
411        use gam_problem::ExecutionPath;
412        // The truthful execution-path classifier must default to the CPU path,
413        // so a result struct that is never told otherwise cannot claim the
414        // device (the original `used_device: bool` defaulted the same way, but
415        // now the "no device" state is a named, non-lying variant).
416        assert_eq!(ExecutionPath::default(), ExecutionPath::Cpu);
417        assert!(!ExecutionPath::Cpu.used_device());
418        assert!(ExecutionPath::GpuResidentFull.used_device());
419    }
420
421    #[test]
422    fn gpu_mode_required_fails_closed_when_device_absent() {
423        use crate::device_runtime::GpuRuntime;
424        // Off always refuses, regardless of hardware.
425        assert!(matches!(
426            GpuRuntime::global_or_fail(GpuPolicy::Off),
427            Err(GpuError::DriverLibraryUnavailable { .. })
428        ));
429
430        if GpuRuntime::is_available() {
431            // On a GPU host both Auto and Required must succeed.
432            assert!(GpuRuntime::global_or_fail(GpuPolicy::Required).is_ok());
433            assert!(GpuRuntime::global_or_fail(GpuPolicy::Auto).is_ok());
434        } else {
435            // Fail-closed: Required surfaces a STRUCTURED error rather than a
436            // silent CPU fallback. Auto also reports unavailable (callers there
437            // swallow it and fall back), but the variant is what lets Required
438            // propagate it as fatal.
439            let required = GpuRuntime::global_or_fail(GpuPolicy::Required);
440            assert!(
441                matches!(required, Err(GpuError::DriverLibraryUnavailable { .. })),
442                "GpuPolicy::Required must fail closed when the device is absent, got {required:?}"
443            );
444            assert!(GpuRuntime::global_or_fail(GpuPolicy::Auto).is_err());
445        }
446    }
447
448    #[test]
449    fn pirls_loop_admission_requires_runtime_size_and_known_family() {
450        use crate::policy::{PirlsLoopAdmission, PirlsLoopCurvatureKind, PirlsLoopFamilyKind};
451        let pol = GpuDispatchPolicy::default();
452        let base = PirlsLoopAdmission {
453            n: 80_000,
454            p: 44,
455            family: Some(PirlsLoopFamilyKind::BernoulliLogit),
456            curvature: PirlsLoopCurvatureKind::Fisher,
457            gpu_available: true,
458        };
459        assert!(pol.should_use_gpu_pirls_loop(base));
460        // No runtime → never dispatch.
461        assert!(!pol.should_use_gpu_pirls_loop(PirlsLoopAdmission {
462            gpu_available: false,
463            ..base
464        }));
465        // Below dense-work floor.
466        assert!(!pol.should_use_gpu_pirls_loop(PirlsLoopAdmission { n: 1_000, ..base }));
467        // Small n with large p is admitted because 2*n*p^2 clears the work floor.
468        assert!(pol.should_use_gpu_pirls_loop(PirlsLoopAdmission {
469            n: 2_000,
470            p: 2_048,
471            ..base
472        }));
473        // Below column floor.
474        assert!(!pol.should_use_gpu_pirls_loop(PirlsLoopAdmission { p: 8, ..base }));
475        // Custom family (not in 6 JIT-cached set) declines.
476        assert!(!pol.should_use_gpu_pirls_loop(PirlsLoopAdmission {
477            family: None,
478            ..base
479        }));
480    }
481
482    #[test]
483    fn required_policy_reports_unsupported_kernel() {
484        let decision = GpuDecision {
485            policy: GpuPolicy::Required,
486            kernel: GpuKernel::DenseXtWX,
487            use_gpu: false,
488            reason: "gpu-required-unsupported",
489        };
490        let err = decision.require_supported().unwrap_err();
491        assert!(err.contains("dense-xtwx"));
492        assert!(err.contains("gpu=required"));
493    }
494}