Skip to main content

gam_gpu/
device_runtime.rs

1#[cfg(target_os = "linux")]
2use std::cell::Cell;
3#[cfg(target_os = "linux")]
4use std::collections::HashMap;
5#[cfg(target_os = "linux")]
6use std::panic::{self, AssertUnwindSafe, catch_unwind};
7use std::sync::OnceLock;
8use std::sync::atomic::{AtomicU64, Ordering};
9#[cfg(target_os = "linux")]
10use std::sync::{Arc, Mutex};
11
12use super::device::GpuDeviceInfo;
13use super::gpu_error::GpuError;
14use super::policy::GpuDispatchPolicy;
15#[cfg(target_os = "linux")]
16use cudarc::driver::{CudaContext, result, sys};
17
18#[path = "runtime_diagnostics.rs"]
19pub(crate) mod diagnostics;
20
21#[derive(Clone, Debug)]
22#[must_use]
23pub struct GpuRuntime {
24    /// Highest-scoring probed CUDA device. Existing dispatch code routes
25    /// one-shot kernels through this device.
26    pub device: GpuDeviceInfo,
27    /// All usable CUDA devices discovered at probe time, ordered by score.
28    pub devices: Vec<GpuDeviceInfo>,
29    pub policy: GpuDispatchPolicy,
30    pub memory_budget_bytes: usize,
31}
32
33static CPU_REASON: OnceLock<String> = OnceLock::new();
34
35/// A genuine reason CUDA cannot exist on this host. These states are distinct
36/// from [`GpuError`]: absence is an expected hardware/platform fact under
37/// [`GpuPolicy::Auto`](super::GpuPolicy::Auto), whereas an error means a CUDA
38/// installation or device that was present failed to initialize correctly.
39#[derive(Clone, Debug, Eq, PartialEq)]
40pub enum GpuAbsence {
41    UnsupportedPlatform,
42    DriverUnavailable { reason: String },
43    NoDevice { reason: String },
44}
45
46impl std::fmt::Display for GpuAbsence {
47    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48        match self {
49            Self::UnsupportedPlatform => {
50                f.write_str("CUDA support is unavailable on this platform")
51            }
52            Self::DriverUnavailable { reason } | Self::NoDevice { reason } => {
53                f.write_str(reason)
54            }
55        }
56    }
57}
58
59/// Lossless result of the process-wide CUDA probe.
60#[derive(Debug)]
61pub enum GpuAvailability {
62    Available(GpuRuntime),
63    Absent(GpuAbsence),
64}
65
66/// Borrowed lossless availability view returned from the one-time cache.
67#[derive(Clone, Copy, Debug)]
68pub enum GpuAvailabilityRef<'a> {
69    Available(&'a GpuRuntime),
70    Absent(&'a GpuAbsence),
71}
72
73/// Process-wide count of lossless runtime-resolution calls.
74///
75/// Incremented on every [`GpuRuntime::availability`] call before the one-time probe
76/// runs — so it counts the moments at which the device probe (and thus CUDA
77/// primary-context creation on each GPU, `cuDevicePrimaryCtxRetain`) could be
78/// triggered. Size-gated accessors that short-circuit for CPU-sized problems
79/// deliberately do not resolve availability, so a test can pin this counter across
80/// such a call and prove the CPU-sized decision path made ZERO driver contact.
81///
82/// Cross-platform (not `cfg(target_os = "linux")`) so the laziness/ordering
83/// contract is testable on CUDA-less hosts: even where the probe itself is a
84/// no-op, the invariant we verify is that the size check precedes resolution.
85static RESOLUTION_CALLS: AtomicU64 = AtomicU64::new(0);
86
87/// Install a process-wide panic hook (idempotent) that drops cudarc's
88/// `panic_no_lib_found` message instead of writing it to stderr. All other
89/// panics flow to the previously installed hook unchanged. The site cudarc
90/// 0.19 panics from is `cudarc-0.19.7/src/lib.rs:200` inside its dynamic
91/// loader; messages from that path start with `Unable to dynamically load`.
92/// Caller code wraps the same cudarc entry points in `catch_unwind`, so the
93/// panic is recovered — this hook just prevents the stderr noise that made
94/// operators think the fit had crashed.
95#[cfg(target_os = "linux")]
96fn install_cudarc_panic_filter() {
97    static HOOK_INSTALLED: OnceLock<()> = OnceLock::new();
98    HOOK_INSTALLED.get_or_init(|| {
99        let prior = panic::take_hook();
100        panic::set_hook(Box::new(move |info| {
101            let payload = info.payload();
102            let message = payload
103                .downcast_ref::<&'static str>()
104                .copied()
105                .or_else(|| payload.downcast_ref::<String>().map(String::as_str))
106                .unwrap_or("");
107            if message.starts_with("Unable to dynamically load") {
108                return;
109            }
110            prior(info);
111        }));
112    });
113}
114
115impl GpuRuntime {
116    pub fn probe() -> Result<GpuAvailability, GpuError> {
117        #[cfg(not(target_os = "linux"))]
118        {
119            let reason = "CUDA support not compiled into this build";
120            Self::record_cpu_reason(reason);
121            diagnostics::log_cuda_disabled(reason);
122            return Ok(GpuAvailability::Absent(GpuAbsence::UnsupportedPlatform));
123        }
124
125        #[cfg(target_os = "linux")]
126        {
127            // `cudarc 0.19`'s entry points lazily initialize the CUDA driver
128            // through generated `culib()` helpers. On CPU-only Linux hosts the
129            // first such call emits `panic_no_lib_found` before unwinding, which
130            // polluted large-scale logs even when the panic was later caught and the
131            // fit fell back to CPU. Keep the preflight completely outside
132            // cudarc: use gam's own `libloading` probe first, and only touch
133            // cudarc after the platform loader can open `libcuda`.
134            //
135            // The preflight does not always agree with cudarc's own loader
136            // candidate list (e.g. large-scale workbench images expose CUDA *runtime*
137            // stub libraries under `/usr/local/cuda-*/targets/.../lib` but no
138            // driver `libcuda.so` in any loader path), so we additionally
139            // install a panic-hook filter that suppresses cudarc's
140            // `panic_no_lib_found` message and wrap every cudarc entry point
141            // below in `catch_unwind` to convert the panic into a typed
142            // `GpuError::DriverCallFailed` instead.
143            install_cudarc_panic_filter();
144            // #1017 probe-first fix: establish cudarc's primary context P and
145            // initialize the CUDA runtime ON IT as the VERY FIRST CUDA action -- before
146            // gam's libloading libcuda preload, the compute-lib dlopens, and device_count.
147            // The clean cuda_context_for-first path works; the probe-first path failed
148            // because a pre-context CUDA touch left the runtime bound to a non-P context,
149            // so later cuBLAS/cuSOLVER handle creation on the P-stream returned
150            // NOT_INITIALIZED. Making cuda_context_for the first action replicates the
151            // working clean path (CudaContext::new loads libcuda + retains the primary +
152            // ensure runs the runtime init); on a CPU-only host it returns None cleanly
153            // via the panic filter + catch_unwind, and the preload check below still runs.
154            let primary_ready = cuda_context_for(0).is_some();
155            log::trace!("[GPU] probe pre-init primary context + runtime: {primary_ready}");
156            match crate::driver::preload_cuda_driver() {
157                Ok(()) => {}
158                Err(GpuError::DriverLibraryUnavailable { reason }) => {
159                    Self::record_cpu_reason(reason.clone());
160                    log::info!("[GPU] CUDA acceleration disabled: {reason}");
161                    diagnostics::log_cuda_disabled(&reason);
162                    return Ok(GpuAvailability::Absent(GpuAbsence::DriverUnavailable {
163                        reason,
164                    }));
165                }
166                Err(error) => return Err(error),
167            }
168
169            // Driver-only environments (e.g. large-scale workbench images that expose
170            // `libcuda.so.1` but ship no cuBLAS/cuSOLVER/cuSPARSE) used to slip
171            // past the libcuda preflight, enable the runtime, and then panic
172            // out of cudarc's `panic_no_lib_found` on the first `CudaBlas::new`
173            // — the panic crossed the PyO3 FFI boundary as a
174            // `ValueError: fit_table panicked inside Rust boundary: Unable to
175            // dynamically load the "cublas" shared library`. The compute
176            // libraries are dispatch-critical (every cuBLAS / cuSOLVER /
177            // cuSPARSE site under `src/gpu/` calls `CudaBlas::new` /
178            // `DnHandle::new` / cusparse handle creation eagerly during
179            // workspace allocation), so we refuse to advertise GPU unless all
180            // three load cleanly here.
181            for stem in ["cublas", "cusolver", "cusparse"] {
182                if let Err(error) = crate::driver::require_cuda_compute_library(stem) {
183                    let reason = format!("lib{stem} unavailable: {error}");
184                    Self::record_cpu_reason(reason.clone());
185                    log::info!("[GPU] CUDA acceleration disabled: {reason}");
186                    diagnostics::log_cuda_disabled(&reason);
187                    return Err(GpuError::RuntimeDependencyUnavailable { reason });
188                }
189            }
190
191            // cudarc 0.19's `culib()` panics via `panic_no_lib_found` when its
192            // own (separate from gam's) dynamic-loader candidate list cannot
193            // find libcuda — this can happen even after our `preload_cuda_driver`
194            // succeeds, for example if our probe loaded a CUDA stub library but
195            // cudarc's loader searches a disjoint set of names. Convert any such
196            // panic into a typed probe failure so the runtime cleanly disables
197            // CUDA and the CPU fallback proceeds without alarming stderr noise.
198            let device_count = match catch_unwind(AssertUnwindSafe(CudaContext::device_count)) {
199                Err(_) => {
200                    return Err(GpuError::DriverCallFailed {
201                        reason: "cudarc failed after the CUDA driver preflight succeeded"
202                            .to_string(),
203                    });
204                }
205                Ok(Ok(count)) => count,
206                Ok(Err(error)) => {
207                    // `device_count` performs `cuInit`, so this is the first
208                    // moment the host's kernel driver actually answers. A
209                    // refusal that is an ENVIRONMENT fact (userland CUDA
210                    // libraries with no matching kernel driver — the container
211                    // / CPU-node case #2267 hit as
212                    // `CUDA_ERROR_SYSTEM_DRIVER_MISMATCH`) is typed absence:
213                    // Auto falls back to CPU, Required still refuses with the
214                    // same diagnosis. Anything else stays a probe fault.
215                    if let Some(absence) = absence_from_driver_init_error(&error) {
216                        let reason = absence.to_string();
217                        Self::record_cpu_reason(reason.clone());
218                        log::info!("[GPU] CUDA acceleration disabled: {reason}");
219                        diagnostics::log_cuda_disabled(&reason);
220                        return Ok(GpuAvailability::Absent(absence));
221                    }
222                    return Err(GpuError::DriverCallFailed {
223                        reason: error.to_string(),
224                    });
225                }
226            };
227            if device_count <= 0 {
228                let reason = "CUDA driver reported no devices";
229                Self::record_cpu_reason(reason);
230                diagnostics::log_cuda_disabled(reason);
231                return Ok(GpuAvailability::Absent(GpuAbsence::NoDevice {
232                    reason: reason.to_string(),
233                }));
234            }
235
236            let mut devices = Vec::new();
237            for ordinal in
238                0..usize::try_from(device_count).map_err(|_| GpuError::DriverCallFailed {
239                    reason: "negative CUDA device count".into(),
240                })?
241            {
242                let ctx = cuda_context_for(ordinal).ok_or_else(|| {
243                    gpu_err!("failed to create CUDA context for device {ordinal}")
244                })?;
245                catch_unwind(AssertUnwindSafe(|| ctx.bind_to_thread()))
246                    .map_err(|_| GpuError::DriverCallFailed {
247                        reason: "CUDA context binding panicked after driver discovery".to_string(),
248                    })?
249                    .map_err(|err| GpuError::DriverCallFailed {
250                        reason: err.to_string(),
251                    })?;
252                devices.push(
253                    catch_unwind(AssertUnwindSafe(|| cuda_device_info(ordinal, &ctx))).map_err(
254                        |_| GpuError::DriverCallFailed {
255                            reason: "CUDA device inspection panicked after driver discovery"
256                                .to_string(),
257                        },
258                    )??,
259                );
260            }
261
262            devices.sort_by(|a, b| b.score().total_cmp(&a.score()));
263            let Some(device) = devices.first().cloned() else {
264                Self::record_cpu_reason("CUDA driver reported no usable devices");
265                diagnostics::log_cuda_disabled("CUDA driver reported no usable devices");
266                return Ok(GpuAvailability::Absent(GpuAbsence::NoDevice {
267                    reason: "CUDA driver reported no usable devices".to_string(),
268                }));
269            };
270
271            let policy = crate::calibration::calibrated_policy_for_device(&device);
272            let memory_budget_bytes = device.memory_budget_bytes();
273            diagnostics::log_cuda_enabled(&device, &policy);
274            diagnostics::log_cuda_pool(&devices);
275
276            Ok(GpuAvailability::Available(Self {
277                device,
278                devices,
279                policy,
280                memory_budget_bytes,
281            }))
282        }
283    }
284
285    /// Return the cached probe outcome without collapsing faults into absence.
286    pub fn availability() -> Result<GpuAvailabilityRef<'static>, GpuError> {
287        // Record every entry BEFORE the `OnceLock` probe, so the size-gated
288        // accessors below (which never reach this point for CPU-sized problems)
289        // can be proven not to have triggered a device probe / context creation.
290        RESOLUTION_CALLS.fetch_add(1, Ordering::Relaxed);
291        static RUNTIME: OnceLock<Result<GpuAvailability, GpuError>> = OnceLock::new();
292        let cached = RUNTIME.get_or_init(|| {
293            let outcome = Self::probe();
294            if let Err(error) = &outcome {
295                let reason = error.to_string();
296                Self::record_cpu_reason(reason.clone());
297                diagnostics::log_cuda_disabled(&reason);
298            }
299            // Install the dense-GEMM dispatch hook exactly when a usable
300            // device was probed. Without this, `gam_linalg::faer_ndarray::fast_ab`
301            // (and the `fast_atb`/`fast_av`/`xt_diag_x` family) never sees a
302            // dispatcher — `gpu_dispatch()` stays `None` — so every dense
303            // product in the engine silently runs on the CPU even when the
304            // V100 is present and the workload clears the policy flop floor.
305            // The hook is a first-write-wins `OnceLock` keyed only on the
306            // presence of a runtime; registering it here, inside the same
307            // `get_or_init` that decides the runtime, guarantees it is
308            // installed before any `fast_ab` caller can observe an available
309            // runtime. The policy gate inside each `try_*` still decides
310            // CPU-vs-GPU per call, so small products are unaffected.
311            if matches!(&outcome, Ok(GpuAvailability::Available(_))) {
312                gam_linalg::gpu_hook::register_gpu_dispatch(Box::new(
313                    super::linalg_dispatch::CudaGemmDispatch,
314                ));
315            }
316            outcome
317        });
318        match cached {
319            Ok(GpuAvailability::Available(runtime)) => {
320                Ok(GpuAvailabilityRef::Available(runtime))
321            }
322            Ok(GpuAvailability::Absent(reason)) => Ok(GpuAvailabilityRef::Absent(reason)),
323            Err(error) => Err(error.clone()),
324        }
325    }
326
327    /// Resolve CUDA under an explicit policy. `Ok(None)` is reserved for a
328    /// genuine absence under Auto/Off; probe faults always remain `Err`, and
329    /// Required converts absence into `RequiredDeviceUnavailable`.
330    pub fn resolve(policy: super::GpuPolicy) -> Result<Option<&'static Self>, GpuError> {
331        if policy == super::GpuPolicy::Off {
332            return Ok(None);
333        }
334        Self::resolve_availability(policy, Self::availability())
335    }
336
337    fn resolve_availability<'a>(
338        policy: super::GpuPolicy,
339        availability: Result<GpuAvailabilityRef<'a>, GpuError>,
340    ) -> Result<Option<&'a Self>, GpuError> {
341        match availability? {
342            GpuAvailabilityRef::Available(runtime) => Ok(Some(runtime)),
343            GpuAvailabilityRef::Absent(_reason) if policy == super::GpuPolicy::Auto => Ok(None),
344            GpuAvailabilityRef::Absent(reason) => Err(GpuError::RequiredDeviceUnavailable {
345                reason: reason.to_string(),
346            }),
347        }
348    }
349
350    /// Resolve CUDA under Required semantics and return the device handle.
351    pub fn require() -> Result<&'static Self, GpuError> {
352        Self::resolve(super::GpuPolicy::Required)?.ok_or_else(|| {
353            GpuError::RequiredDeviceUnavailable {
354                reason: "required CUDA runtime resolved to an absent state".to_string(),
355            }
356        })
357    }
358
359    /// Number of times [`Self::availability`] has been entered process-wide.
360    ///
361    /// Test-facing instrumentation for the laziness contract: a size-gated
362    /// caller that returns before resolving availability leaves this unchanged, so
363    /// a test can assert a CPU-sized decision path created no CUDA context. This
364    /// is a monotone call counter, NOT a probe-success flag.
365    #[must_use]
366    pub fn resolution_call_count() -> u64 {
367        RESOLUTION_CALLS.load(Ordering::Relaxed)
368    }
369
370    /// Size-gated [`Self::resolve`]: resolve the process-wide runtime only when the
371    /// estimated dense arithmetic `work_flops` clears the GPU-dispatch flop floor.
372    ///
373    /// This is the ordering fix for the CUDA startup tax. For a CPU-sized problem
374    /// (`work_flops` below the floor) it returns `Ok(None)` without calling
375    /// [`Self::resolve`], so the device probe — and the `cuDevicePrimaryCtxRetain`
376    /// primary-context creation it performs on every GPU — never runs. The
377    /// problem-size decision therefore strictly precedes any driver contact, and
378    /// a CPU-sized fit pays ZERO CUDA cost.
379    ///
380    /// The floor is [`GpuDispatchPolicy::MIN_CALIBRATABLE_GEMM_FLOPS`] — the
381    /// smallest `gemm_min_flops` ANY reachable policy (default seed or
382    /// device-calibrated) can carry, known WITHOUT a device — so the gate never
383    /// needs a probe to decide it should not probe, and refusing below it can
384    /// never block work that any policy would have dispatched. Work at or above
385    /// the floor falls through to the identical lossless resolution path (where
386    /// the real, possibly calibrated policy still gates each op), so device
387    /// behaviour for genuinely GPU-sized problems is unchanged.
388    pub fn resolve_if_dense_work_exceeds_floor(
389        policy: super::GpuPolicy,
390        work_flops: u128,
391    ) -> Result<Option<&'static Self>, GpuError> {
392        if work_flops < GpuDispatchPolicy::MIN_CALIBRATABLE_GEMM_FLOPS {
393            return Ok(None);
394        }
395        Self::resolve(policy)
396    }
397
398    #[must_use]
399    pub fn policy(&self) -> &GpuDispatchPolicy {
400        &self.policy
401    }
402
403    #[must_use]
404    pub fn selected_device(&self) -> &GpuDeviceInfo {
405        &self.device
406    }
407
408    #[must_use]
409    pub(crate) fn cpu_reason() -> Option<&'static str> {
410        CPU_REASON.get().map(String::as_str)
411    }
412
413    fn record_cpu_reason(reason: impl Into<String>) {
414        CPU_REASON.set(reason.into()).ok();
415    }
416}
417
418/// Classify a CUDA driver-*initialization* failure that is a fact about the
419/// host environment rather than a fault of a device that was present.
420///
421/// `cuInit` is the first call the kernel driver answers. The codes below all
422/// mean "CUDA cannot work on this host as configured" — a loaded `libcuda`
423/// userland with a missing, older, or mismatched kernel driver, a linker stub
424/// standing in for the real library, or no attached device. Those states are
425/// [`GpuAbsence`] by this module's own definition (absence is an expected
426/// hardware/platform fact under `GpuPolicy::Auto`): container images and CPU
427/// nodes routinely carry CUDA userland libraries they cannot back with a
428/// driver, and a fit under Auto must fall back to CPU there instead of dying
429/// inside runtime resolution (#2267). Every other code — illegal address,
430/// out-of-memory, ECC faults, ... — still means "a CUDA installation that was
431/// present failed", and stays a probe fault.
432#[cfg(target_os = "linux")]
433fn absence_from_driver_init_error(error: &result::DriverError) -> Option<GpuAbsence> {
434    use sys::cudaError_enum as CudaErrorCode;
435    // Format the raw enum code, NEVER the DriverError itself: cudarc's
436    // Display/Debug for DriverError resolve the error string through its
437    // dynamic loader (`culib()`), which panics via `panic_no_lib_found` on
438    // exactly the driverless hosts this classifier exists for. The enum's
439    // derived Debug is a pure Rust name and is safe everywhere.
440    let code = error.0;
441    let classification = match code {
442        CudaErrorCode::CUDA_ERROR_NO_DEVICE => {
443            return Some(GpuAbsence::NoDevice {
444                reason: format!(
445                    "CUDA driver initialized but reports no attached device ({code:?})"
446                ),
447            });
448        }
449        CudaErrorCode::CUDA_ERROR_STUB_LIBRARY => {
450            "the loaded libcuda is a linker stub, not a real driver"
451        }
452        // NOTE: there is deliberately no INSUFFICIENT_DRIVER arm — that code
453        // (`cudaErrorInsufficientDriver`) exists only in the CUDA *runtime*
454        // API; the driver API reports the userland/kernel version split as
455        // `CUDA_ERROR_SYSTEM_DRIVER_MISMATCH` below.
456        CudaErrorCode::CUDA_ERROR_SYSTEM_NOT_READY => {
457            "the CUDA system is not ready (kernel driver or fabric daemon not running)"
458        }
459        CudaErrorCode::CUDA_ERROR_SYSTEM_DRIVER_MISMATCH => {
460            "the CUDA userland libraries do not match the host kernel driver"
461        }
462        CudaErrorCode::CUDA_ERROR_COMPAT_NOT_SUPPORTED_ON_DEVICE => {
463            "CUDA forward-compatibility mode is not supported on the visible device"
464        }
465        _ => return None,
466    };
467    Some(GpuAbsence::DriverUnavailable {
468        reason: format!("CUDA initialization refused: {classification} ({code:?})"),
469    })
470}
471
472/// Make the CUDA **runtime** API usable on `ordinal`.
473///
474/// gam drives the GPU through the CUDA *driver* API (cudarc [`CudaContext`]),
475/// which materialises the driver primary context but never selects a device for
476/// the CUDA *runtime* API. cuBLAS / cuSOLVER are runtime-based, so `cublasCreate`
477/// / `cusolverDnCreate` return `CUBLAS_STATUS_NOT_INITIALIZED` /
478/// `CUSOLVER_STATUS_NOT_INITIALIZED` until the runtime has a current device —
479/// which silently disables *every* GPU linear-algebra path (the dispatch sites
480/// map the handle error to `Unavailable` and fall back to CPU). We select the
481/// device on the calling host thread (cheap, idempotent) and force one-time
482/// runtime primary-context materialisation per device via the canonical
483/// `cudaMalloc`/`cudaFree` idiom, so every downstream handle creation succeeds.
484#[cfg(target_os = "linux")]
485fn ensure_cuda_runtime_device(ordinal: usize) {
486    let Ok(o) = i32::try_from(ordinal) else {
487        return;
488    };
489    // SAFETY: the `runtime` cudarc feature is enabled; cudaSetDevice on a valid
490    // ordinal is idempotent and per-host-thread.
491    let set_rc = unsafe { cudarc::runtime::sys::cudaSetDevice(o) };
492    log::trace!("[GPU] runtime cudaSetDevice({o}) -> {set_rc:?}");
493    // Materialise the runtime primary context for this device: cuBLAS/cuSOLVER
494    // `*Create` use whatever context is current at creation time, so the runtime
495    // device must be selected and its primary context materialised before a
496    // handle is made. A 256-byte allocate-then-free is the canonical,
497    // ~microsecond way to force it. This is invoked exactly once per (thread,
498    // ordinal) by `bind_and_touch_runtime` — the NOT_INITIALIZED condition it
499    // repairs is per-thread-per-device and does NOT re-arm per call once the
500    // primary context is current and the runtime is materialised on the thread.
501    let mut p: *mut core::ffi::c_void = core::ptr::null_mut();
502    // SAFETY: forces runtime primary-context creation on the current device.
503    let malloc_rc = unsafe { cudarc::runtime::sys::cudaMalloc(&mut p as *mut _ as *mut _, 256) };
504    log::trace!("[GPU] runtime cudaMalloc -> {malloc_rc:?}");
505    if !p.is_null() {
506        // SAFETY: `p` is the live device allocation returned just above.
507        let free_rc = unsafe { cudarc::runtime::sys::cudaFree(p) };
508        log::trace!("[GPU] runtime cudaFree -> {free_rc:?}");
509    }
510}
511
512#[cfg(target_os = "linux")]
513thread_local! {
514    /// The device ordinal whose primary context is bound as THIS thread's
515    /// current context AND whose runtime primary context has already been
516    /// materialised on this thread. `Some(ordinal)` means the last
517    /// [`cuda_context_for`] touch on this thread was `ordinal` and nothing has
518    /// switched it since, so the per-call `bind_to_thread` + runtime
519    /// materialisation can be skipped.
520    ///
521    /// Switching to a different ordinal (or the initial `None`) invalidates the
522    /// memo and forces a full rebind + re-materialisation, so the per-thread-
523    /// per-device NOT_INITIALIZED repair (#1017) is preserved exactly: the
524    /// condition it fixes is arm-once-per-(thread, device), and a memo keyed on
525    /// the thread's currently-bound ordinal only skips work when that same
526    /// ordinal is already current — i.e. when neither the driver context nor the
527    /// runtime device could have drifted.
528    static BOUND_RUNTIME_ORDINAL: Cell<Option<usize>> = const { Cell::new(None) };
529}
530
531/// Bind cudarc's primary context for `ordinal` current on this thread and
532/// materialise the runtime primary context on it — memoised once per (thread,
533/// ordinal).
534///
535/// The bind + runtime touch exist to repair the probe-first
536/// CUBLAS/CUSOLVER_STATUS_NOT_INITIALIZED bug: on a fresh solve thread the
537/// cached-context path would let the CUDA runtime initialise its OWN device
538/// context, so a later `cublasCreate`/`cusolverDnCreate` on the primary-context
539/// stream fails. Binding the primary context current and forcing runtime
540/// materialisation on the SAME context before returning fixes it. That repair
541/// is durable per (thread, ordinal); it does not re-arm per call. So when this
542/// thread's current context is already `ordinal` we skip the bind and the
543/// 256-byte cudaMalloc/cudaFree entirely, removing the per-call driver tax while
544/// preserving the invariant — a switch to any other ordinal re-runs the full
545/// repair.
546#[cfg(target_os = "linux")]
547fn bind_and_touch_runtime(ordinal: usize, ctx: &Arc<CudaContext>) {
548    if BOUND_RUNTIME_ORDINAL.with(Cell::get) == Some(ordinal) {
549        return;
550    }
551    let bound = catch_unwind(AssertUnwindSafe(|| ctx.bind_to_thread()));
552    log::trace!(
553        "[GPU] cuda_context_for bind ok={} ordinal={ordinal}",
554        matches!(bound, Ok(Ok(())))
555    );
556    ensure_cuda_runtime_device(ordinal);
557    // Latch the memo only after a SUCCESSFUL bind: a failed bind left the
558    // thread's current context indeterminate, so the next call must retry the
559    // full repair rather than assume `ordinal` is current.
560    if matches!(bound, Ok(Ok(()))) {
561        BOUND_RUNTIME_ORDINAL.with(|c| c.set(Some(ordinal)));
562    }
563}
564
565#[cfg(target_os = "linux")]
566pub fn cuda_context_for(ordinal: usize) -> Option<Arc<CudaContext>> {
567    static CONTEXTS: OnceLock<Mutex<HashMap<usize, Arc<CudaContext>>>> = OnceLock::new();
568    let contexts = CONTEXTS.get_or_init(|| Mutex::new(HashMap::new()));
569    if let Some(ctx) = contexts.lock().ok()?.get(&ordinal).cloned() {
570        bind_and_touch_runtime(ordinal, &ctx);
571        return Some(ctx);
572    }
573    // cudarc 0.19 panics from `panic_no_lib_found` if its loader fails to
574    // locate libcuda. Demote that to `None` so the runtime probe surfaces a
575    // typed `DriverUnavailable` rather than tearing down the worker thread.
576    let ctx = catch_unwind(AssertUnwindSafe(|| CudaContext::new(ordinal)))
577        .ok()?
578        .ok()?;
579    let out = {
580        let mut guard = contexts.lock().ok()?;
581        guard.entry(ordinal).or_insert_with(|| ctx.clone()).clone()
582    };
583    // CudaContext::new already bound the primary context, but the HashMap may return
584    // an entry created on another thread; the memoised bind rebinds so the primary
585    // context is current on THIS thread before the runtime touch (same probe-first
586    // NOT_INITIALIZED guard) on the first touch, and is a no-op thereafter.
587    bind_and_touch_runtime(ordinal, &out);
588    Some(out)
589}
590
591#[cfg(target_os = "linux")]
592fn cuda_device_info(ordinal: usize, ctx: &CudaContext) -> Result<GpuDeviceInfo, GpuError> {
593    result::init().map_err(|err| GpuError::DriverCallFailed {
594        reason: err.to_string(),
595    })?;
596    let device =
597        result::device::get(
598            i32::try_from(ordinal).map_err(|_| GpuError::DriverCallFailed {
599                reason: "device ordinal overflow".into(),
600            })?,
601        )
602        .map_err(|err| GpuError::DriverCallFailed {
603            reason: err.to_string(),
604        })?;
605    let attr = |attribute| -> Result<i32, GpuError> {
606        // SAFETY: device comes from cudarc's validated device::get.
607        unsafe { result::device::get_attribute(device, attribute) }.map_err(|err| {
608            GpuError::DriverCallFailed {
609                reason: err.to_string(),
610            }
611        })
612    };
613    let (free_mem_bytes, total_mem_bytes) =
614        ctx.mem_get_info()
615            .map_err(|err| GpuError::DriverCallFailed {
616                reason: err.to_string(),
617            })?;
618    let major = attr(sys::CUdevice_attribute_enum::CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR)?;
619    let minor = attr(sys::CUdevice_attribute_enum::CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR)?;
620    Ok(GpuDeviceInfo {
621        ordinal,
622        name: result::device::get_name(device).unwrap_or_else(|_| format!("CUDA device {ordinal}")),
623        capability: super::device::GpuCapability::from_compute_capability(major, minor),
624        sm_count: attr(sys::CUdevice_attribute_enum::CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT)?,
625        max_threads_per_sm: attr(
626            sys::CUdevice_attribute_enum::CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR,
627        )?,
628        max_shared_mem_per_block: attr(
629            sys::CUdevice_attribute_enum::CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK,
630        )
631        .unwrap_or(0) as usize,
632        l2_cache_bytes: attr(sys::CUdevice_attribute_enum::CU_DEVICE_ATTRIBUTE_L2_CACHE_SIZE)
633            .unwrap_or(0) as usize,
634        total_mem_bytes,
635        free_mem_bytes,
636        ecc_enabled: attr(sys::CUdevice_attribute_enum::CU_DEVICE_ATTRIBUTE_ECC_ENABLED)
637            .unwrap_or(0)
638            != 0,
639        integrated: attr(sys::CUdevice_attribute_enum::CU_DEVICE_ATTRIBUTE_INTEGRATED).unwrap_or(0)
640            != 0,
641        mig_mode: false,
642    })
643}
644
645#[cfg(test)]
646mod module_path_lock_tests {
647    //! Locks the canonical module path for the GPU device runtime so a future
648    //! rename is a deliberate, reviewed change (precedent: issue #1157's
649    //! "lock module path" tests). This file was renamed from the generic,
650    //! colliding `gpu/runtime.rs` to `gpu/device_runtime.rs` under issue #1137.
651
652    #[test]
653    fn gpu_device_runtime_module_path_is_canonical() {
654        // Resolving `GpuRuntime` through the `device_runtime` module path
655        // pins the honest name; if the module is renamed this stops compiling.
656        _ = crate::device_runtime::GpuRuntime::resolution_call_count();
657        let type_name = std::any::type_name::<crate::device_runtime::GpuRuntime>();
658        assert!(
659            type_name.contains("device_runtime"),
660            "GpuRuntime must live in the `device_runtime` module (got {type_name})"
661        );
662    }
663}
664
665#[cfg(test)]
666mod laziness_gate_tests {
667    //! Pins the CUDA startup-tax ordering fix: a CPU-sized problem must reach
668    //! its size decision WITHOUT ever resolving GPU availability (which is what
669    //! triggers the one-time device probe + `cuDevicePrimaryCtxRetain`
670    //! primary-context creation on every GPU). Runs on any host — on a CUDA-less
671    //! box the probe is a no-op, but the invariant under test is purely the
672    //! control-flow ordering (size check strictly before resolution), which is
673    //! observable through the process-wide `resolution_call_count` counter.
674    //!
675    //! nextest runs each test in its own process, so the counter starts at a
676    //! clean baseline per test; the assertions use a delta against `before` so
677    //! they are robust regardless of the absolute starting value.
678    use super::*;
679
680    #[test]
681    fn cpu_sized_dense_work_never_resolves_availability() {
682        let before = GpuRuntime::resolution_call_count();
683        // Dense work far below the GPU-dispatch flop floor: a CPU-sized fit.
684        assert!(
685            GpuRuntime::resolve_if_dense_work_exceeds_floor(super::super::GpuPolicy::Auto, 1_000)
686                .expect("the pre-probe size gate itself is infallible")
687                .is_none(),
688            "CPU-sized work must not select the device"
689        );
690        assert_eq!(
691            GpuRuntime::resolution_call_count(),
692            before,
693            "the size gate must short-circuit BEFORE resolution/probe for CPU-sized \
694             work, so no CUDA context is ever created"
695        );
696    }
697
698    /// The resolution counter is process-global and the test binary runs in
699    /// parallel: on a real GPU box dozens of concurrent tests legitimately
700    /// enter `availability()` between any two reads (this is exactly how the
701    /// exact `before + 1` form of these gates failed on hardware while
702    /// staying green on quiet CPU-only runners — #2313's hardware-only
703    /// coverage class). Calling the gate `N` times and bounding the delta
704    /// makes the control-flow property immune to that traffic: a gate that
705    /// probes contributes ≥ N calls; one that never probes contributes 0,
706    /// and unrelated concurrent traffic is orders of magnitude below N.
707    const COUNTER_PROBE_CALLS: u64 = 4096;
708
709    #[test]
710    fn gpu_sized_dense_work_falls_through_to_resolution() {
711        let before = GpuRuntime::resolution_call_count();
712        // Above any plausible floor: every call must consult the runtime,
713        // i.e. the gate does not change behaviour for genuinely GPU-sized
714        // problems. The returned handle is irrelevant here (None on CPU-only
715        // boxes); the observable is the consultation count below.
716        for _ in 0..COUNTER_PROBE_CALLS {
717            let runtime = GpuRuntime::resolve_if_dense_work_exceeds_floor(
718                super::super::GpuPolicy::Auto,
719                u128::MAX,
720            )
721            .expect("a probe fault must fail this gate instead of looking absent");
722            assert!(
723                runtime.is_none_or(|runtime| !runtime.devices.is_empty()),
724                "an available runtime must expose at least one usable device"
725            );
726        }
727        assert!(
728            GpuRuntime::resolution_call_count() - before >= COUNTER_PROBE_CALLS,
729            "GPU-sized work must fall through to availability resolution on every call"
730        );
731    }
732
733    #[test]
734    fn floor_is_the_min_calibratable_gemm_threshold() {
735        // The gate's floor is the smallest gemm_min_flops any reachable policy
736        // (default seed OR device-calibrated) can carry — known without a
737        // device, so the decision to NOT probe never needs a probe, and the
738        // refusal can never block work some calibrated policy would dispatch.
739        let floor = GpuDispatchPolicy::MIN_CALIBRATABLE_GEMM_FLOPS;
740        let before = GpuRuntime::resolution_call_count();
741        for _ in 0..COUNTER_PROBE_CALLS {
742            assert!(
743                GpuRuntime::resolve_if_dense_work_exceeds_floor(
744                    super::super::GpuPolicy::Auto,
745                    floor - 1,
746                )
747                .expect("the below-floor gate cannot probe or fail")
748                .is_none()
749            );
750        }
751        let below_floor_delta = GpuRuntime::resolution_call_count() - before;
752        assert!(
753            below_floor_delta < COUNTER_PROBE_CALLS,
754            "below-floor work must never probe the runtime: {below_floor_delta} \
755             resolution entries during {COUNTER_PROBE_CALLS} below-floor calls"
756        );
757        // At the floor the gate must consult the runtime (fall through) on
758        // every call.
759        let at_floor_before = GpuRuntime::resolution_call_count();
760        for _ in 0..COUNTER_PROBE_CALLS {
761            let runtime = GpuRuntime::resolve_if_dense_work_exceeds_floor(
762                super::super::GpuPolicy::Auto,
763                floor,
764            )
765            .expect("a probe fault must fail the boundary gate instead of looking absent");
766            assert!(
767                runtime.is_none_or(|runtime| !runtime.devices.is_empty()),
768                "a successful floor-boundary probe must expose at least one usable device"
769            );
770        }
771        assert!(
772            GpuRuntime::resolution_call_count() - at_floor_before >= COUNTER_PROBE_CALLS,
773            "floor-boundary work must fall through to availability resolution on every call"
774        );
775    }
776}
777
778#[cfg(test)]
779mod policy_resolution_contract_tests {
780    use super::*;
781    use crate::GpuPolicy;
782
783    #[test]
784    fn auto_maps_only_typed_absence_to_none() {
785        let absence = GpuAbsence::NoDevice {
786            reason: "synthetic device-free absence".to_string(),
787        };
788        let resolved = GpuRuntime::resolve_availability(
789            GpuPolicy::Auto,
790            Ok(GpuAvailabilityRef::Absent(&absence)),
791        )
792        .expect("typed absence is expected under Auto");
793        assert!(resolved.is_none());
794    }
795
796    #[test]
797    fn required_turns_only_typed_absence_into_required_unavailable() {
798        let absence = GpuAbsence::DriverUnavailable {
799            reason: "synthetic missing driver".to_string(),
800        };
801        let error = GpuRuntime::resolve_availability(
802            GpuPolicy::Required,
803            Ok(GpuAvailabilityRef::Absent(&absence)),
804        )
805        .expect_err("Required must reject typed absence");
806        assert!(matches!(
807            error,
808            GpuError::RequiredDeviceUnavailable { ref reason }
809                if reason == "synthetic missing driver"
810        ));
811    }
812
813    /// #2267: a CUDA userland whose kernel driver is missing or mismatched is
814    /// an environment fact. `cuInit`-boundary refusals of that class must be
815    /// typed absence — Auto proceeds on CPU, Required refuses with the same
816    /// diagnosis — never a probe fault that kills the fit under Auto.
817    #[cfg(target_os = "linux")]
818    #[test]
819    fn driver_mismatch_at_init_is_typed_absence_not_a_fault() {
820        for code in [
821            sys::cudaError_enum::CUDA_ERROR_SYSTEM_DRIVER_MISMATCH,
822            sys::cudaError_enum::CUDA_ERROR_STUB_LIBRARY,
823            sys::cudaError_enum::CUDA_ERROR_SYSTEM_NOT_READY,
824            sys::cudaError_enum::CUDA_ERROR_COMPAT_NOT_SUPPORTED_ON_DEVICE,
825        ] {
826            let absence = absence_from_driver_init_error(&result::DriverError(code))
827                .unwrap_or_else(|| panic!("{code:?} is an environment fact, not a device fault"));
828            assert!(
829                matches!(absence, GpuAbsence::DriverUnavailable { .. }),
830                "{code:?} must classify as an unavailable driver"
831            );
832            let resolved =
833                GpuRuntime::resolve_availability(GpuPolicy::Auto, Ok(GpuAvailabilityRef::Absent(&absence)))
834                    .expect("Auto must accept driver-environment absence");
835            assert!(resolved.is_none(), "Auto must fall back to CPU on {code:?}");
836            let required_error = GpuRuntime::resolve_availability(
837                GpuPolicy::Required,
838                Ok(GpuAvailabilityRef::Absent(&absence)),
839            )
840            .expect_err("Required must refuse driver-environment absence");
841            assert!(
842                matches!(required_error, GpuError::RequiredDeviceUnavailable { .. }),
843                "Required must carry the environment diagnosis for {code:?}"
844            );
845        }
846        let no_device = absence_from_driver_init_error(&result::DriverError(
847            sys::cudaError_enum::CUDA_ERROR_NO_DEVICE,
848        ))
849        .expect("no attached device is an environment fact");
850        assert!(matches!(no_device, GpuAbsence::NoDevice { .. }));
851    }
852
853    /// Faults of a present CUDA installation must never be reclassified into
854    /// absence — the Auto policy is allowed to hide missing hardware, never a
855    /// broken device.
856    #[cfg(target_os = "linux")]
857    #[test]
858    fn present_device_faults_never_classify_as_absence() {
859        for code in [
860            sys::cudaError_enum::CUDA_ERROR_ILLEGAL_ADDRESS,
861            sys::cudaError_enum::CUDA_ERROR_OUT_OF_MEMORY,
862            sys::cudaError_enum::CUDA_ERROR_NOT_INITIALIZED,
863            sys::cudaError_enum::CUDA_ERROR_ECC_UNCORRECTABLE,
864            sys::cudaError_enum::CUDA_ERROR_UNKNOWN,
865        ] {
866            assert!(
867                absence_from_driver_init_error(&result::DriverError(code)).is_none(),
868                "{code:?} is a fault of present hardware and must stay a probe fault"
869            );
870        }
871    }
872
873    #[test]
874    fn auto_and_required_preserve_probe_fault_variants() {
875        for policy in [GpuPolicy::Auto, GpuPolicy::Required] {
876            let error = GpuRuntime::resolve_availability(
877                policy,
878                Err(GpuError::RuntimeDependencyUnavailable {
879                    reason: "synthetic missing cuBLAS".to_string(),
880                }),
881            )
882            .expect_err("probe faults must never project to absence");
883            assert!(matches!(
884                error,
885                GpuError::RuntimeDependencyUnavailable { ref reason }
886                    if reason == "synthetic missing cuBLAS"
887            ));
888        }
889    }
890}
891
892#[cfg(all(test, target_os = "linux"))]
893mod tests {
894    use super::*;
895
896    /// On a CPU-only host (no `libcuda.dylib` / `libcuda.so` reachable via the
897    /// platform loader), exercising every cudarc-touching entry point in this
898    /// crate must produce a clean `None`/`Err` and never trigger
899    /// `cudarc::panic_no_lib_found`. This is the regression guard for issues
900    /// #168 and #176, which observed a `PanicException` escaping the PyO3
901    /// boundary on macOS when `sae_manifold_fit(..., atom_basis="duchon")` or
902    /// `d_atom=1` ran on a host with no CUDA driver.
903    ///
904    /// On a host where libcuda *is* present the test still passes — it asserts
905    /// only that calls don't panic and that `is_culib_present()` agrees with
906    /// the typed availability result about the absence of a driver.
907    #[test]
908    fn cpu_only_host_never_panics_on_gpu_entry_points() {
909        // Without libcuda the runtime must report unavailable rather than
910        // panicking from inside `culib()`; with libcuda the runtime may or
911        // may not have a usable device, but the panic-free contract still
912        // holds and the dispatch smoke test below exercises it.
913        match crate::driver::preload_cuda_driver() {
914            Ok(()) => {}
915            Err(GpuError::DriverLibraryUnavailable { .. }) => assert!(
916                matches!(
917                    GpuRuntime::availability(),
918                    Ok(GpuAvailabilityRef::Absent(GpuAbsence::DriverUnavailable { .. }))
919                ),
920                "typed driver absence must remain absence through runtime availability"
921            ),
922            Err(error) => panic!("a present-but-broken CUDA driver must fail this test: {error}"),
923        }
924
925        // Every public GPU dispatch must return a value (no panic) when the
926        // runtime is unavailable. We use minimum-size inputs so a host that
927        // *does* have a GPU still passes (workload below dispatch threshold
928        // → returns None / Err / CPU fallback the same way).
929        use ndarray::{Array1, Array2};
930        let a = Array2::<f64>::zeros((4, 3));
931        let b = Array2::<f64>::zeros((3, 2));
932        let v = Array1::<f64>::zeros(3);
933        let w = Array1::<f64>::ones(4);
934
935        // gpu::linalg_dispatch dispatchers
936        crate::try_fast_ab(a.view(), b.view());
937        crate::try_fast_av(a.view(), v.view());
938        crate::try_fast_atv(a.view(), w.view());
939        let mut chol_in = Array2::<f64>::eye(3);
940        crate::try_cholesky_lower_inplace(&mut chol_in);
941
942        // gpu::solver Cholesky entry points
943        let h = Array2::<f64>::eye(3);
944        let rhs = Array2::<f64>::zeros((3, 1));
945        let solve_outcome = crate::solver::cholesky_solve_gpu(h.view(), rhs.view());
946        let factor_outcome = crate::solver::cholesky_lower_gpu(h.view());
947        match GpuRuntime::availability() {
948            Ok(GpuAvailabilityRef::Absent(_)) => {
949                assert!(
950                    solve_outcome.is_err(),
951                    "cholesky_solve_gpu must Err when runtime is unavailable"
952                );
953                assert!(
954                    factor_outcome.is_err(),
955                    "cholesky_lower_gpu must Err when runtime is unavailable"
956                );
957            }
958            Ok(GpuAvailabilityRef::Available(_)) => {}
959            Err(error) => panic!("GPU probe fault must fail this dispatch smoke test: {error}"),
960        }
961
962        // NOTE: the weighted-crossprod GPU dispatcher with CPU fallback
963        // (`weighted_crossprod_gpu`) moved out of this crate to `gam-solve`
964        // (`gpu::pirls_gpu`) during the #1521 crate carve, since it depends on
965        // the higher-level PIRLS assembly. Its panic-free / Ok-via-CPU-fallback
966        // contract is now exercised by a regression test there
967        // (`weighted_crossprod_gpu_cpu_fallback_*`), not from gam-gpu, which
968        // cannot reach gam-solve without a dependency cycle.
969    }
970}