use std::sync::OnceLock;
use crate::runtime::Device;
use crate::runtime::traits::profile::DeviceProfile;
const MAX_CACHED_DEVICES: usize = 16;
static PROFILE_CACHE: [OnceLock<DeviceProfile>; MAX_CACHED_DEVICES] =
[const { OnceLock::new() }; MAX_CACHED_DEVICES];
#[derive(Clone, Debug)]
pub struct CudaDevice {
pub(crate) index: usize,
}
fn ensure_driver_init() -> Result<(), CudaError> {
cudarc::driver::result::init()
.map_err(|e| CudaError::DeviceError(format!("Failed to initialize CUDA driver: {e:?}")))
}
impl CudaDevice {
pub fn new(index: usize) -> Self {
Self { index }
}
pub fn compute_capability(&self) -> Result<(u32, u32), CudaError> {
ensure_driver_init()?;
let device = cudarc::driver::result::device::get(self.index as i32).map_err(|e| {
CudaError::DeviceError(format!("Failed to get CUDA device {}: {:?}", self.index, e))
})?;
let major = unsafe {
cudarc::driver::result::device::get_attribute(
device,
cudarc::driver::sys::CUdevice_attribute::CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR,
)
}
.map_err(|e| CudaError::DeviceError(format!("Failed to get compute capability major: {:?}", e)))? as u32;
let minor = unsafe {
cudarc::driver::result::device::get_attribute(
device,
cudarc::driver::sys::CUdevice_attribute::CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR,
)
}
.map_err(|e| CudaError::DeviceError(format!("Failed to get compute capability minor: {:?}", e)))? as u32;
Ok((major, minor))
}
pub fn sync(&self) -> Result<(), CudaError> {
cudarc::driver::result::ctx::synchronize().map_err(|e| {
CudaError::SyncError(format!(
"Failed to synchronize CUDA context for device {}: {:?}",
self.index, e
))
})
}
pub fn memory_info(&self) -> Result<(u64, u64), CudaError> {
let (free, total) = cudarc::driver::result::mem_get_info().map_err(|e| {
CudaError::DeviceError(format!(
"Failed to get memory info for device {}: {:?}",
self.index, e
))
})?;
Ok((free as u64, total as u64))
}
pub fn available_memory(&self) -> Result<u64, CudaError> {
let (free, _) = self.memory_info()?;
Ok(free)
}
pub fn total_memory(&self) -> Result<u64, CudaError> {
let device = self.driver_device()?;
let total = unsafe { cudarc::driver::result::device::total_mem(device) }.map_err(|e| {
CudaError::DeviceError(format!(
"Failed to get the total memory of CUDA device {}: {:?}",
self.index, e
))
})?;
Ok(total as u64)
}
pub fn product_name(&self) -> Result<String, CudaError> {
let device = self.driver_device()?;
cudarc::driver::result::device::get_name(device).map_err(|e| {
CudaError::DeviceError(format!(
"Failed to get the name of CUDA device {}: {:?}",
self.index, e
))
})
}
pub fn count() -> Result<usize, CudaError> {
if !unsafe { cudarc::driver::sys::is_culib_present() } {
return Ok(0);
}
ensure_driver_init()?;
let count = cudarc::driver::result::device::get_count()
.map_err(|e| CudaError::DeviceError(format!("Failed to count CUDA devices: {e:?}")))?;
Ok(usize::try_from(count).unwrap_or(0))
}
fn driver_device(&self) -> Result<cudarc::driver::sys::CUdevice, CudaError> {
ensure_driver_init()?;
cudarc::driver::result::device::get(self.index as i32).map_err(|e| {
CudaError::DeviceError(format!("Failed to get CUDA device {}: {:?}", self.index, e))
})
}
fn query_profile(&self) -> DeviceProfile {
let Ok((major, minor)) = self.compute_capability() else {
return DeviceProfile::unknown("cuda");
};
if ensure_driver_init().is_err() {
return DeviceProfile::unknown("cuda");
}
let Ok(device) = cudarc::driver::result::device::get(self.index as i32) else {
return DeviceProfile::unknown("cuda");
};
let get_attr = |attr: cudarc::driver::sys::CUdevice_attribute| -> Option<u32> {
unsafe { cudarc::driver::result::device::get_attribute(device, attr) }
.ok()
.and_then(|v| u32::try_from(v).ok())
};
let (Some(compute_units), Some(shared_mem_per_block), Some(shared_mem_per_unit), Some(max_threads_per_block), Some(lane_width)) = (
get_attr(cudarc::driver::sys::CUdevice_attribute::CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT),
get_attr(cudarc::driver::sys::CUdevice_attribute::CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK),
get_attr(
cudarc::driver::sys::CUdevice_attribute::CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_MULTIPROCESSOR,
),
get_attr(cudarc::driver::sys::CUdevice_attribute::CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK),
get_attr(cudarc::driver::sys::CUdevice_attribute::CU_DEVICE_ATTRIBUTE_WARP_SIZE),
)
else {
return DeviceProfile::unknown("cuda");
};
let (arch, caps) = DeviceProfile::arch_and_caps_for_compute_capability(major, minor);
DeviceProfile {
backend: "cuda",
arch,
compute_units,
shared_mem_per_block,
shared_mem_per_unit,
max_threads_per_block,
lane_width,
caps,
}
}
}
impl Device for CudaDevice {
fn id(&self) -> usize {
self.index
}
fn name(&self) -> String {
format!("cuda:{}", self.index)
}
fn profile(&self) -> DeviceProfile {
match PROFILE_CACHE.get(self.index) {
Some(slot) => *slot.get_or_init(|| self.query_profile()),
None => self.query_profile(),
}
}
}
impl Default for CudaDevice {
fn default() -> Self {
Self::new(0)
}
}
#[derive(Debug, Clone)]
pub enum CudaError {
DeviceError(String),
AllocationError(String),
CopyError(String),
KernelError(String),
SyncError(String),
CublasError(String),
ContextError(String),
}
impl std::fmt::Display for CudaError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
CudaError::DeviceError(msg) => write!(f, "CUDA device error: {}", msg),
CudaError::AllocationError(msg) => write!(f, "CUDA allocation error: {}", msg),
CudaError::CopyError(msg) => write!(f, "CUDA copy error: {}", msg),
CudaError::KernelError(msg) => write!(f, "CUDA kernel error: {}", msg),
CudaError::SyncError(msg) => write!(f, "CUDA sync error: {}", msg),
CudaError::CublasError(msg) => write!(f, "cuBLAS error: {}", msg),
CudaError::ContextError(msg) => write!(f, "CUDA context error: {}", msg),
}
}
}
impl std::error::Error for CudaError {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn name_and_memory_answer_before_any_client() {
let count = CudaDevice::count().unwrap_or_else(|e| panic!("counting devices: {e}"));
if count == 0 {
eprintln!("skipping: no CUDA device");
return;
}
let device = CudaDevice::new(0);
let name = device
.product_name()
.unwrap_or_else(|e| panic!("device name: {e}"));
assert!(!name.is_empty());
let total = device
.total_memory()
.unwrap_or_else(|e| panic!("total memory: {e}"));
assert!(total > 0);
}
}