1#[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
39pub 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
55use 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#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
88#[serde(rename_all = "kebab-case")]
89pub enum GpuPolicy {
90 #[default]
92 Auto,
93 Off,
95 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#[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 match POLICY.get() {
178 Some(p) => *p,
179 None => GpuPolicy::Auto,
180 }
181}
182
183pub fn configure_global_policy(policy: GpuPolicy) {
190 POLICY.set(policy).ok();
192}
193
194#[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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
217pub enum GpuEligibility {
218 BackendNotCompiled,
220 WorkloadBelowThreshold,
223 Eligible,
226}
227
228impl GpuEligibility {
229 #[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
244pub fn decide(kernel: GpuKernel, eligibility: GpuEligibility) -> GpuDecision {
248 let policy = global_policy();
249 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 (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
307pub 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 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 assert!(matches!(
426 GpuRuntime::global_or_fail(GpuPolicy::Off),
427 Err(GpuError::DriverLibraryUnavailable { .. })
428 ));
429
430 if GpuRuntime::is_available() {
431 assert!(GpuRuntime::global_or_fail(GpuPolicy::Required).is_ok());
433 assert!(GpuRuntime::global_or_fail(GpuPolicy::Auto).is_ok());
434 } else {
435 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 assert!(!pol.should_use_gpu_pirls_loop(PirlsLoopAdmission {
462 gpu_available: false,
463 ..base
464 }));
465 assert!(!pol.should_use_gpu_pirls_loop(PirlsLoopAdmission { n: 1_000, ..base }));
467 assert!(pol.should_use_gpu_pirls_loop(PirlsLoopAdmission {
469 n: 2_000,
470 p: 2_048,
471 ..base
472 }));
473 assert!(!pol.should_use_gpu_pirls_loop(PirlsLoopAdmission { p: 8, ..base }));
475 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}