1use std::process::Command;
4
5use serde::{Deserialize, Serialize};
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
9#[serde(rename_all = "snake_case")]
10#[non_exhaustive]
11pub enum Accel {
12 Nvidia,
13 Amd,
14 Apple,
15 Cpu,
16}
17
18#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
19pub struct Gpu {
20 pub accel: Accel,
21 pub name: String,
22 pub memory_bytes: u64,
24 pub unified: bool,
26 pub compute_capability: Option<(u32, u32)>,
28 pub driver: Option<String>,
29}
30
31#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
32pub struct Hardware {
33 pub os: String,
34 pub arch: String,
35 pub cpu_threads: usize,
36 pub ram_bytes: u64,
37 pub gpus: Vec<Gpu>,
38}
39
40impl Hardware {
41 pub fn accel(&self) -> Accel {
43 self.gpus.first().map(|g| g.accel).unwrap_or(Accel::Cpu)
44 }
45
46 pub fn unified(&self) -> bool {
48 self.gpus.first().is_none_or(|g| g.unified)
49 }
50
51 pub fn vllm_supported(&self) -> bool {
54 self.os == "linux" && self.gpus.iter().any(|g| g.accel == Accel::Nvidia && g.compute_capability.is_some_and(|(major, _)| major >= 8))
55 }
56
57 pub fn needs_cuda13(&self) -> bool {
59 self.gpus.iter().any(|g| g.accel == Accel::Nvidia && g.compute_capability.is_some_and(|(major, minor)| major >= 12 && minor >= 1))
60 }
61}
62
63pub fn detect() -> Hardware {
65 let ram_bytes = system_memory().unwrap_or(0);
66 let mut gpus = Vec::new();
67 if let Some(out) = run("nvidia-smi", &["--query-gpu=name,memory.total,compute_cap,driver_version", "--format=csv,noheader,nounits"]) {
68 gpus.extend(parse_nvidia_smi(&out, ram_bytes));
69 }
70 if gpus.is_empty() {
71 gpus.extend(amd_sysfs(ram_bytes));
72 }
73 if gpus.is_empty() && cfg!(target_os = "macos") && cfg!(target_arch = "aarch64") {
74 gpus.push(Gpu {
75 accel: Accel::Apple,
76 name: apple_chip().unwrap_or_else(|| "Apple silicon".into()),
77 memory_bytes: ram_bytes,
78 unified: true,
79 compute_capability: None,
80 driver: None,
81 });
82 }
83 Hardware {
84 os: std::env::consts::OS.into(),
85 arch: std::env::consts::ARCH.into(),
86 cpu_threads: std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1),
87 ram_bytes,
88 gpus,
89 }
90}
91
92fn run(program: &str, args: &[&str]) -> Option<String> {
93 let out = Command::new(program).args(args).output().ok()?;
94 out.status.success().then(|| String::from_utf8_lossy(&out.stdout).into_owned())
95}
96
97fn system_memory() -> Option<u64> {
98 if cfg!(any(target_os = "linux", target_os = "android")) {
99 return parse_meminfo_total(&std::fs::read_to_string("/proc/meminfo").ok()?);
100 }
101 if cfg!(target_os = "windows") {
102 let out = run("powershell", &["-NoProfile", "-Command", "(Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory"])?;
103 return out.trim().parse().ok();
104 }
105 if cfg!(any(target_os = "macos", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd")) {
106 let key = if cfg!(target_os = "macos") { "hw.memsize" } else { "hw.physmem" };
107 return run("sysctl", &["-n", key])?.trim().parse().ok();
108 }
109 None
110}
111
112fn apple_chip() -> Option<String> {
113 run("sysctl", &["-n", "machdep.cpu.brand_string"]).map(|s| s.trim().to_string()).filter(|s| !s.is_empty())
114}
115
116pub fn parse_meminfo_total(meminfo: &str) -> Option<u64> {
118 let line = meminfo.lines().find(|l| l.starts_with("MemTotal:"))?;
119 let kib: u64 = line.split_whitespace().nth(1)?.parse().ok()?;
120 Some(kib * 1024)
121}
122
123pub fn parse_nvidia_smi(csv: &str, ram_bytes: u64) -> Vec<Gpu> {
126 csv.lines()
127 .filter_map(|line| {
128 let cols: Vec<&str> = line.split(',').map(str::trim).collect();
129 if cols.len() < 4 || cols[0].is_empty() {
130 return None;
131 }
132 let mib = cols[1].parse::<u64>().ok();
133 let cc = cols[2].split_once('.').and_then(|(a, b)| Some((a.parse().ok()?, b.parse().ok()?)));
134 let unified = mib.is_none() || cols[0].contains("GB10");
135 Some(Gpu {
136 accel: Accel::Nvidia,
137 name: cols[0].to_string(),
138 memory_bytes: if unified { ram_bytes } else { mib.unwrap_or(0) * 1024 * 1024 },
139 unified,
140 compute_capability: cc,
141 driver: Some(cols[3].to_string()).filter(|d| !d.is_empty()),
142 })
143 })
144 .collect()
145}
146
147fn amd_sysfs(ram_bytes: u64) -> Vec<Gpu> {
148 let Ok(entries) = std::fs::read_dir("/sys/class/drm") else { return Vec::new() };
149 let mut gpus = Vec::new();
150 for entry in entries.flatten() {
151 let name = entry.file_name().to_string_lossy().into_owned();
152 if !name.starts_with("card") || name.contains('-') {
153 continue;
154 }
155 let dev = entry.path().join("device");
156 if std::fs::read_to_string(dev.join("vendor")).map(|v| v.trim() != "0x1002").unwrap_or(true) {
157 continue;
158 }
159 let vram: u64 = std::fs::read_to_string(dev.join("mem_info_vram_total")).ok().and_then(|s| s.trim().parse().ok()).unwrap_or(0);
160 let unified = vram < 4 * super::GIB;
162 gpus.push(Gpu {
163 accel: Accel::Amd,
164 name: "AMD GPU".into(),
165 memory_bytes: if unified { ram_bytes } else { vram },
166 unified,
167 compute_capability: None,
168 driver: None,
169 });
170 }
171 gpus
172}
173
174#[cfg(test)]
175mod tests {
176 use super::*;
177
178 #[test]
179 fn nvidia_discrete() {
180 let gpus = parse_nvidia_smi("NVIDIA GeForce RTX 3060, 12288, 8.6, 615.78.08\n", 64 << 30);
181 assert_eq!(gpus.len(), 1);
182 assert_eq!(gpus[0].memory_bytes, 12 << 30);
183 assert!(!gpus[0].unified);
184 assert_eq!(gpus[0].compute_capability, Some((8, 6)));
185 }
186
187 #[test]
188 fn gb10_is_unified() {
189 let gpus = parse_nvidia_smi("NVIDIA GB10, [N/A], 12.1, 580.95.05\n", 128 << 30);
190 assert!(gpus[0].unified);
191 assert_eq!(gpus[0].memory_bytes, 128 << 30);
192 let hw = Hardware { os: "linux".into(), arch: "aarch64".into(), cpu_threads: 20, ram_bytes: 128 << 30, gpus };
193 assert!(hw.vllm_supported());
194 assert!(hw.needs_cuda13());
195 }
196
197 #[test]
198 fn meminfo() {
199 assert_eq!(parse_meminfo_total("MemTotal: 65536 kB\nMemFree: 1 kB\n"), Some(65536 * 1024));
200 }
201
202 #[test]
203 fn detect_does_not_panic() {
204 let hw = detect();
205 assert!(hw.cpu_threads >= 1);
206 }
207}