use std::sync::OnceLock;
#[cfg(target_os = "linux")]
use crate::device::common::constants::google_tpu::is_libtpu_available;
use crate::device::common::execute_command_default;
pub fn has_nvidia() -> bool {
static CACHE: OnceLock<bool> = OnceLock::new();
*CACHE.get_or_init(detect_nvidia)
}
fn detect_nvidia() -> bool {
if std::env::consts::OS == "macos" {
if let Ok(output) = execute_command_default("system_profiler", &["SPPCIDataType"])
&& output.status == 0
{
if output.stdout.contains("NVIDIA") {
return true;
}
}
if let Ok(output) = execute_command_default("nvidia-smi", &["-L"])
&& output.status == 0
{
return output
.stdout
.lines()
.any(|line| line.trim().starts_with("GPU"));
}
return false;
}
if std::env::consts::OS == "windows" {
if let Ok(output) = execute_command_default("nvidia-smi", &["-L"])
&& output.status == 0
{
let has_gpu = output.stdout.lines().any(|line| {
let trimmed = line.trim();
trimmed.starts_with("GPU") && trimmed.contains(":")
});
if has_gpu {
return true;
}
}
return false;
}
if let Ok(output) = execute_command_default("lspci", &[])
&& output.status == 0
{
for line in output.stdout.lines() {
if (line.contains("VGA") || line.contains("3D")) && line.contains("NVIDIA") {
return true;
}
}
}
if let Ok(output) = execute_command_default("nvidia-smi", &["-L"]) {
if output.status == 0 {
let has_gpu = output.stdout.lines().any(|line| {
let trimmed = line.trim();
trimmed.starts_with("GPU") && trimmed.contains(":")
});
if has_gpu {
return true;
}
}
if output.stderr.contains("No devices were found")
|| output.stderr.contains("Failed to initialize NVML")
{
return false;
}
}
false
}
#[cfg(all(target_os = "linux", not(target_env = "musl")))]
pub fn has_amd() -> bool {
static CACHE: OnceLock<bool> = OnceLock::new();
*CACHE.get_or_init(detect_amd)
}
pub fn has_intel_gpu() -> bool {
static CACHE: OnceLock<bool> = OnceLock::new();
*CACHE.get_or_init(detect_intel_gpu)
}
fn detect_intel_gpu() -> bool {
#[cfg(target_os = "linux")]
{
crate::device::readers::intel_gpu_linux::has_intel_client_gpu()
}
#[cfg(target_os = "windows")]
{
crate::device::readers::intel_gpu_windows::has_intel_gpu_windows()
}
#[cfg(not(any(target_os = "linux", target_os = "windows")))]
{
false
}
}
#[cfg(all(target_os = "linux", not(target_env = "musl")))]
fn detect_amd() -> bool {
if std::env::consts::OS == "linux" {
if let Ok(output) = execute_command_default("lspci", &["-n"])
&& output.status == 0
{
for line in output.stdout.lines() {
if line.contains(":1002:") {
return true;
}
}
}
if let Ok(entries) = std::fs::read_dir("/sys/class/drm") {
for entry in entries.flatten() {
let path = entry.path().join("device/vendor");
if let Ok(vendor) = std::fs::read_to_string(path)
&& vendor.trim() == "0x1002"
{
return true;
}
}
}
}
false
}
pub fn is_jetson() -> bool {
static CACHE: OnceLock<bool> = OnceLock::new();
*CACHE.get_or_init(detect_jetson)
}
fn detect_jetson() -> bool {
if let Ok(compatible) = std::fs::read_to_string("/proc/device-tree/compatible") {
return compatible.contains("tegra");
}
false
}
pub fn is_apple_silicon() -> bool {
static CACHE: OnceLock<bool> = OnceLock::new();
*CACHE.get_or_init(detect_apple_silicon)
}
fn detect_apple_silicon() -> bool {
if std::env::consts::OS != "macos" {
return false;
}
if cfg!(all(target_os = "macos", target_arch = "aarch64")) {
return true;
}
if is_translated_process() {
return true;
}
match execute_command_default("uname", &["-m"]) {
Ok(output) => output.stdout.trim() == "arm64",
Err(_) => false,
}
}
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
fn is_translated_process() -> bool {
matches!(
execute_command_default("sysctl", &["-n", "sysctl.proc_translated"]),
Ok(output) if output.status == 0 && output.stdout.trim() == "1"
)
}
#[cfg(not(all(target_os = "macos", target_arch = "x86_64")))]
fn is_translated_process() -> bool {
false
}
#[cfg(target_os = "macos")]
pub fn is_intel_mac() -> bool {
!is_apple_silicon()
}
pub fn has_furiosa() -> bool {
static CACHE: OnceLock<bool> = OnceLock::new();
*CACHE.get_or_init(detect_furiosa)
}
fn detect_furiosa() -> bool {
let rngd_mgmt_path = std::path::Path::new("/sys/class/rngd_mgmt");
if !rngd_mgmt_path.exists() {
return false;
}
let npu0_mgmt_path = rngd_mgmt_path.join("rngd!npu0mgmt");
if !npu0_mgmt_path.exists() {
return false;
}
let platform_type_path = npu0_mgmt_path.join("platform_type");
if let Ok(platform_type) = std::fs::read_to_string(platform_type_path)
&& platform_type.trim() == "FuriosaAI"
{
return true;
}
false
}
#[cfg(target_os = "linux")]
pub fn has_tenstorrent() -> bool {
static CACHE: OnceLock<bool> = OnceLock::new();
*CACHE.get_or_init(detect_tenstorrent)
}
#[cfg(target_os = "linux")]
fn detect_tenstorrent() -> bool {
if std::path::Path::new("/dev/tenstorrent").exists() {
return true;
}
if std::env::consts::OS == "macos" {
if let Ok(output) = execute_command_default("system_profiler", &["SPPCIDataType"])
&& output.status == 0
&& output.stdout.contains("Tenstorrent")
{
return true;
}
} else {
if let Ok(output) = execute_command_default("lspci", &[])
&& output.status == 0
{
if output.stdout.contains("Tenstorrent") {
return true;
}
}
}
if let Ok(output) = execute_command_default("tt-smi", &["-s", "--snapshot_no_tty"])
&& output.status == 0
{
return output.stdout.contains("device_info");
}
false
}
pub fn has_rebellions() -> bool {
static CACHE: OnceLock<bool> = OnceLock::new();
*CACHE.get_or_init(detect_rebellions)
}
fn detect_rebellions() -> bool {
if std::path::Path::new("/dev/rbln0").exists() {
return true;
}
if std::env::consts::OS == "macos" {
if let Ok(output) = execute_command_default("system_profiler", &["SPPCIDataType"])
&& output.status == 0
&& (output.stdout.contains("Rebellions") || output.stdout.contains("RBLN"))
{
return true;
}
} else {
if let Ok(output) = execute_command_default("lspci", &[])
&& output.status == 0
{
if output.stdout.contains("1f3f:") || output.stdout.contains("Rebellions") {
return true;
}
}
}
for cmd in &[
"rbln-stat",
"/usr/local/bin/rbln-stat",
"/usr/bin/rbln-stat",
"rbln-smi",
"/usr/local/bin/rbln-smi",
"/usr/bin/rbln-smi",
] {
if let Ok(output) = execute_command_default(cmd, &["-j"])
&& output.status == 0
{
if output.stdout.contains("\"devices\"") && output.stdout.contains("\"uuid\"") {
return true;
}
}
}
false
}
#[cfg(target_os = "linux")]
pub fn has_google_tpu() -> bool {
static CACHE: OnceLock<bool> = OnceLock::new();
*CACHE.get_or_init(detect_google_tpu)
}
#[cfg(target_os = "linux")]
fn detect_google_tpu() -> bool {
if let Ok(entries) = std::fs::read_dir("/dev") {
for entry in entries.flatten() {
if let Some(name) = entry.file_name().to_str()
&& name.starts_with("accel")
{
let sysfs_path = format!("/sys/class/accel/{name}/device/vendor");
if let Ok(vendor) = std::fs::read_to_string(&sysfs_path)
&& vendor.trim() == "0x1ae0"
{
return true;
}
}
}
}
if std::env::var("TPU_NAME").is_ok()
|| std::env::var("TPU_CHIPS_PER_HOST_BOUNDS").is_ok()
|| std::env::var("CLOUD_TPU_TASK_ID").is_ok()
|| std::env::var("TPU_ACCELERATOR_TYPE").is_ok()
|| std::env::var("TPU_WORKER_ID").is_ok()
|| std::env::var("TPU_WORKER_HOSTNAMES").is_ok()
{
return true;
}
if is_libtpu_available() {
if let Ok(pjrt_names) = std::env::var("PJRT_DEVICE")
&& pjrt_names.to_lowercase().contains("tpu")
{
return true;
}
if let Ok(product) = std::fs::read_to_string("/sys/class/dmi/id/product_name")
&& product.to_lowercase().contains("google")
{
return true;
}
}
false
}
pub fn has_gaudi() -> bool {
static CACHE: OnceLock<bool> = OnceLock::new();
*CACHE.get_or_init(detect_gaudi)
}
fn detect_gaudi() -> bool {
if std::path::Path::new("/dev/accel/accel0").exists() {
let sysfs_path = "/sys/class/accel/accel0/device/vendor";
if let Ok(vendor) = std::fs::read_to_string(sysfs_path) {
if vendor.trim() == "0x1ae0" {
} else {
return true;
}
} else {
return true;
}
}
if std::path::Path::new("/dev/hl0").exists() {
return true;
}
const PATHS: &[&str] = &[
"/usr/bin/hl-smi",
"/usr/local/bin/hl-smi",
"/opt/habanalabs/bin/hl-smi",
];
for path in PATHS {
if std::path::Path::new(path).exists() {
return true;
}
}
if std::env::consts::OS == "linux" {
if let Ok(output) = execute_command_default("lspci", &["-n"])
&& output.status == 0
{
for line in output.stdout.lines() {
if line.contains("1da3:") {
return true;
}
}
}
if let Ok(output) = execute_command_default("lspci", &[])
&& output.status == 0
{
let stdout_lower = output.stdout.to_lowercase();
if stdout_lower.contains("habana") || stdout_lower.contains("gaudi") {
return true;
}
}
}
if let Ok(output) = execute_command_default("hl-smi", &["-L"])
&& output.status == 0
{
return !output.stdout.is_empty();
}
false
}
pub fn get_os_type() -> &'static str {
std::env::consts::OS
}
#[allow(dead_code)]
pub fn is_running_in_container() -> bool {
if std::env::consts::OS != "linux" {
return false;
}
if std::path::Path::new("/.dockerenv").exists() {
return true;
}
if std::env::var("KUBERNETES_SERVICE_HOST").is_ok() {
return true;
}
if let Ok(cgroup_content) = std::fs::read_to_string("/proc/self/cgroup") {
let container_patterns = [
"docker",
"containerd",
"crio",
"podman",
"garden",
"lxc",
"systemd-nspawn",
];
for pattern in &container_patterns {
if cgroup_content.contains(pattern) {
return true;
}
}
}
if let Ok(sched_content) = std::fs::read_to_string("/proc/1/sched")
&& sched_content.lines().next().is_some_and(|line| {
line.contains("bash") || line.contains("sh") || line.contains("init")
})
{
if !sched_content.contains("systemd") && !sched_content.contains("upstart") {
return true;
}
}
false
}
#[allow(dead_code)]
pub fn get_container_pid_namespace() -> Option<u32> {
if let Ok(ns_link) = std::fs::read_link("/proc/self/ns/pid") {
if let Some(ns_str) = ns_link.to_str() {
if let Some(start) = ns_str.find('[')
&& let Some(end) = ns_str.find(']')
{
let ns_id_str = &ns_str[start + 1..end];
if let Ok(ns_id_u64) = ns_id_str.parse::<u64>() {
let ns_id = ns_id_u64 as u32;
return Some(ns_id);
}
}
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn apple_silicon_detection_is_total_and_stable() {
let first = is_apple_silicon();
assert_eq!(first, is_apple_silicon());
if std::env::consts::OS != "macos" {
assert!(!first, "non-macOS hosts are never Apple Silicon");
}
}
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
#[test]
fn aarch64_macos_build_reports_apple_silicon() {
assert!(is_apple_silicon());
}
#[cfg(target_os = "macos")]
#[test]
fn intel_mac_is_the_macos_complement_of_apple_silicon() {
assert_eq!(is_intel_mac(), !is_apple_silicon());
}
}
pub mod introspection {
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub struct PlatformSnapshot {
pub os: &'static str,
pub nvidia: bool,
pub jetson: bool,
pub amd: bool,
pub apple_silicon: bool,
pub gaudi: bool,
pub google_tpu: bool,
pub tenstorrent: bool,
pub rebellions: bool,
pub furiosa: bool,
pub intel_gpu: bool,
}
pub fn snapshot() -> PlatformSnapshot {
PlatformSnapshot {
os: super::get_os_type(),
nvidia: super::has_nvidia(),
jetson: super::is_jetson(),
amd: detect_amd(),
apple_silicon: super::is_apple_silicon(),
gaudi: super::has_gaudi(),
google_tpu: detect_google_tpu(),
tenstorrent: detect_tenstorrent(),
rebellions: super::has_rebellions(),
furiosa: super::has_furiosa(),
intel_gpu: super::has_intel_gpu(),
}
}
#[cfg(all(target_os = "linux", not(target_env = "musl")))]
fn detect_amd() -> bool {
super::has_amd()
}
#[cfg(not(all(target_os = "linux", not(target_env = "musl"))))]
fn detect_amd() -> bool {
false
}
#[cfg(target_os = "linux")]
fn detect_google_tpu() -> bool {
super::has_google_tpu()
}
#[cfg(not(target_os = "linux"))]
fn detect_google_tpu() -> bool {
false
}
#[cfg(target_os = "linux")]
fn detect_tenstorrent() -> bool {
super::has_tenstorrent()
}
#[cfg(not(target_os = "linux"))]
fn detect_tenstorrent() -> bool {
false
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn snapshot_os_matches_consts() {
let snap = snapshot();
assert_eq!(snap.os, std::env::consts::OS);
}
#[test]
fn snapshot_is_default_friendly() {
let empty = PlatformSnapshot::default();
assert_eq!(empty.os, "");
assert!(!empty.nvidia);
assert!(!empty.intel_gpu);
}
}
}