Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
use crate::types::{GpuInfo, GpuUsage};
#[cfg(not(any(target_os = "android", target_os = "ios", target_os = "macos")))]
use {
crate::types::Vendor,
nvml_wrapper::{error::NvmlError, Nvml},
std::sync::RwLock,
};
/// NVML handle. On Linux we use RwLock so we can invalidate after sleep/resume
/// and re-initialize when the driver is ready again.
#[cfg(not(any(target_os = "android", target_os = "ios", target_os = "macos")))]
static NVML: RwLock<Option<Nvml>> = RwLock::new(None);
#[derive(Debug, Clone, serde::Serialize)]
pub struct NvidiaInfo {
pub index: u32,
pub compute_capability: String,
}
/// A CUDA version. NVML reports the one a driver supports as
/// `1000 * major + 10 * minor`, the same number `cuDriverGetVersion` returns.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct CudaVersion {
pub major: u32,
pub minor: u32,
}
impl CudaVersion {
pub fn from_driver_int(v: i32) -> Option<Self> {
let v = u32::try_from(v).ok().filter(|v| *v > 0)?;
Some(Self {
major: v / 1000,
minor: (v % 1000) / 10,
})
}
/// Parses `13.2`, the form `nvcc --version` and the engine report.
pub fn parse(text: &str) -> Option<Self> {
let (major, minor) = text.trim().split_once('.')?;
Some(Self {
major: major.parse().ok()?,
minor: minor.parse().ok()?,
})
}
}
impl std::fmt::Display for CudaVersion {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}.{}", self.major, self.minor)
}
}
/// What the installed NVIDIA driver says about itself.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NvidiaDriver {
/// The driver release, e.g. `595.97`.
pub version: String,
/// The newest CUDA the driver can run, when NVML reports it.
pub cuda: Option<CudaVersion>,
}
/// The installed NVIDIA driver, or None when there is no NVIDIA GPU, NVML does
/// not load, or the platform has no NVIDIA driver.
pub fn nvidia_driver() -> Option<NvidiaDriver> {
#[cfg(any(target_os = "android", target_os = "ios", target_os = "macos"))]
{
None
}
#[cfg(not(any(target_os = "android", target_os = "ios", target_os = "macos")))]
{
with_nvml(|nvml| {
let nvml = nvml?;
let version = nvml.sys_driver_version().ok()?;
let cuda = nvml
.sys_cuda_driver_version()
.ok()
.and_then(CudaVersion::from_driver_int);
Some(NvidiaDriver { version, cuda })
})
}
}
/// Run a closure with the current NVML handle, initializing if needed.
#[cfg(not(any(target_os = "android", target_os = "ios", target_os = "macos")))]
fn with_nvml<F, R>(f: F) -> R
where
F: FnOnce(Option<&Nvml>) -> R,
{
// Try read first for the common case (already initialized)
{
let guard = NVML.read().unwrap_or_else(|e| e.into_inner());
if guard.is_some() {
return f(guard.as_ref());
}
}
// Not initialized or was invalidated: try to init
{
let mut guard = NVML.write().unwrap_or_else(|e| e.into_inner());
if guard.is_none() {
let result = Nvml::init().or_else(|e| {
if cfg!(target_os = "linux") {
log::debug!("NVML init failed, trying Linux fallback: {}", e);
let lib_path = std::ffi::OsStr::new("libnvidia-ml.so.1");
Nvml::builder().lib_path(lib_path).init()
} else {
Err(e)
}
});
match result {
Ok(nvml) => {
log::debug!("NVML initialized successfully");
*guard = Some(nvml);
}
Err(e) => {
log::debug!("Unable to initialize NVML: {}", e);
}
}
}
f(guard.as_ref())
}
}
/// Invalidates the NVML handle so the next use re-initializes. Call after system
/// resume on Linux when the GPU driver state has been reset.
#[cfg(target_os = "linux")]
pub fn invalidate_nvml() {
let mut guard = NVML.write().unwrap_or_else(|e| e.into_inner());
*guard = None;
log::debug!("NVML invalidated (e.g. after resume); will re-init on next use");
}
/// No-op on non-Linux; invalidation is only needed for Linux sleep/resume.
#[cfg(not(target_os = "linux"))]
pub fn invalidate_nvml() {}
impl GpuInfo {
pub fn get_usage_nvidia(&self) -> GpuUsage {
#[cfg(any(target_os = "android", target_os = "ios", target_os = "macos"))]
{
return self.get_usage_unsupported();
}
#[cfg(not(any(target_os = "android", target_os = "ios", target_os = "macos")))]
{
let index = match &self.nvidia_info {
Some(nvidia_info) => nvidia_info.index,
None => {
log::error!("get_usage_nvidia() called on non-NVIDIA GPU");
return self.get_usage_unsupported();
}
};
self.get_nvidia_memory_usage(index)
.unwrap_or_else(|e| {
log::error!("Failed to get memory usage for NVIDIA GPU {}: {}", index, e);
self.get_usage_unsupported()
})
}
}
#[cfg(not(any(target_os = "android", target_os = "ios", target_os = "macos")))]
fn get_nvidia_memory_usage(&self, index: u32) -> Result<GpuUsage, NvmlError> {
with_nvml(|nvml| {
let nvml = nvml.ok_or(NvmlError::Unknown)?;
let device = nvml.device_by_index(index)?;
let mem_info = device.memory_info()?;
Ok(GpuUsage {
uuid: self.uuid.clone(),
used_memory: mem_info.used / (1024 * 1024), // bytes to MiB
total_memory: mem_info.total / (1024 * 1024), // bytes to MiB
})
})
}
}
pub fn get_nvidia_gpus() -> Vec<GpuInfo> {
#[cfg(any(target_os = "android", target_os = "ios", target_os = "macos"))]
{
vec![]
}
#[cfg(not(any(target_os = "android", target_os = "ios", target_os = "macos")))]
{
get_nvidia_gpus_internal()
}
}
#[cfg(not(any(target_os = "android", target_os = "ios", target_os = "macos")))]
fn get_nvidia_gpus_internal() -> Vec<GpuInfo> {
with_nvml(|nvml| {
let nvml = match nvml {
Some(n) => n,
None => {
log::debug!("NVML not available");
return vec![];
}
};
let (num_gpus, driver_version) = match (nvml.device_count(), nvml.sys_driver_version()) {
(Ok(count), Ok(version)) => (count, version),
(Err(e), _) | (_, Err(e)) => {
log::error!("Failed to get NVIDIA system info: {}", e);
return vec![];
}
};
let mut gpus = Vec::with_capacity(num_gpus as usize);
for i in 0..num_gpus {
match create_gpu_info(nvml, i, &driver_version) {
Ok(gpu_info) => gpus.push(gpu_info),
Err(e) => log::warn!("Failed to get info for NVIDIA GPU {}: {}", i, e),
}
}
gpus
})
}
#[cfg(not(any(target_os = "android", target_os = "ios", target_os = "macos")))]
fn create_gpu_info(nvml: &Nvml, index: u32, driver_version: &str) -> Result<GpuInfo, NvmlError> {
let device = nvml.device_by_index(index)?;
let memory_info = device.memory_info()?;
let compute_capability = device.cuda_compute_capability()?;
let uuid = device.uuid()?;
let clean_uuid = if let Some(stripped) = uuid.strip_prefix("GPU-") {
stripped.to_string()
} else {
uuid
};
Ok(GpuInfo {
name: device.name()?,
total_memory: memory_info.total / (1024 * 1024), // bytes to MiB
vendor: Vendor::NVIDIA,
uuid: clean_uuid,
driver_version: driver_version.to_string(),
nvidia_info: Some(NvidiaInfo {
index,
compute_capability: format!("{}.{}", compute_capability.major, compute_capability.minor),
}),
vulkan_info: None,
})
}