crates/state/host/src/lib.rs 37.9 KiB 1060 lines Raw
1 //! inf3r-host — probes real hardware: devices, VRAM, arch, driver.2 //!3 //! The probe answers one question: what can this machine allocate? The core4 //! asks it before it starts a plugin, so a plugin whose `requires` do not match5 //! the host is refused by name (spec section 16.1, requirement R6).6 //!7 //! Every number here is read from the machine. The host has no declared size,8 //! because a declared size that disagrees with the driver is worse than none.9 10 use std::collections::BTreeSet;11 use std::path::{Path, PathBuf};12 use std::process::Command;13 14 mod profile;15 16 pub use profile::{Limits, Mismatch, Profile, ProfileError};17 18 /// One device that a plugin can use.19 #[derive(Clone, PartialEq, Eq, Debug)]20 pub struct Gpu {21     /// The identifier that the catalogue and the operator use: `cuda:0`,22     /// `rocm:0`, `vulkan:0`, `metal:0`, or `cpu:0`.23     pub id: String,24     /// The name that the driver reports.25     pub name: String,26     /// The backend's bus address, which is stable across boots. A discrete27     /// card reports its PCI slot; a CPU or unified-memory device names itself.28     pub bus: String,29     /// Bytes that a process may allocate. `None` is a device whose memory the30     /// host could not measure.31     pub bytes: Option<u64>,32     /// Bytes that the device reports free now. `None` is a device whose free33     /// memory the driver does not expose, so a caller that needs the number34     /// waits on evidence instead of a guess.35     pub free_bytes: Option<u64>,36     /// The compute capability as `sm00` or `gfx0000`. `None` is a driver that37     /// does not report it, so a profile that names one cannot be met.38     pub compute: Option<String>,39 }40 41 impl Gpu {42     /// The backend of this device, taken from the id before the first colon.43     ///44     /// The id is the one name that a bind, a catalogue, and a ledger key all45     /// share, so the backend does not need a second field that could disagree46     /// with it.47     pub fn backend(&self) -> &str {48         backend_of(&self.id)49     }50 }51 52 /// The backend part of a device id: `cuda:1` is `cuda`.53 pub fn backend_of(device: &str) -> &str {54     device55         .split_once(':')56         .map_or(device, |(backend, _)| backend)57 }58 59 /// What the host is and what it has.60 #[derive(Clone, PartialEq, Eq, Debug)]61 pub struct Host {62     /// The architecture that this binary was built for. A binary that runs on63     /// another architecture does not exist.64     pub arch: String,65     /// The driver version, as the NVIDIA or amdgpu driver reports it.66     pub driver: Option<String>,67     /// The CUDA version in the `nvidia-smi` header. `None` is a machine with68     /// no NVIDIA driver or a driver that does not print the version.69     pub cuda: Option<String>,70     /// The devices, grouped by backend in index order: CUDA, ROCm, Vulkan,71     /// Metal, then the CPU.72     pub gpus: Vec<Gpu>,73     /// The shared objects that `ldconfig` lists, without the path.74     pub sonames: BTreeSet<String>,75 }76 77 impl Host {78     /// Reads the machine.79     ///80     /// It probes NVIDIA through `nvidia-smi`, AMD through amdgpu sysfs, Vulkan81     /// through `vulkaninfo --summary`, Metal through unified memory on macOS,82     /// and the CPU through the kernel's own memory counters. It never fails: a83     /// machine without a driver is a machine with no device of that backend,84     /// which is a valid answer to "what can this machine allocate?".85     pub fn probe() -> Host {86         let mut gpus = probe_gpus(Path::new("/proc/driver/nvidia/gpus"), Path::new("/dev"));87         gpus.extend(probe_amd(Path::new(AMD_DRM)));88         gpus.extend(probe_vulkan(&gpus));89         gpus.extend(probe_metal());90         if let Some(cpu) = probe_cpu() {91             gpus.push(cpu);92         }93         Host {94             arch: std::env::consts::ARCH.to_string(),95             driver: probe_driver(Path::new("/proc/driver/nvidia/version"))96                 .or_else(probe_amd_driver),97             cuda: probe_cuda(),98             gpus,99             sonames: probe_sonames(),100         }101     }102 103     /// The device with this identifier.104     pub fn gpu(&self, id: &str) -> Option<&Gpu> {105         self.gpus.iter().find(|gpu| gpu.id == id)106     }107 108     /// Total bytes of every device, including the CPU's own memory.109     pub fn total_bytes(&self) -> u64 {110         self.gpus.iter().filter_map(|gpu| gpu.bytes).sum()111     }112 113     /// Encodes the probe as tab-separated lines.114     ///115     /// The control and the probe helper run in different namespaces, so the116     /// host record crosses as text. The format is one line per field and has117     /// no header: a reader that does not understand a line refuses the probe118     /// rather than silently dropping a device.119     pub fn encode(&self) -> String {120         let mut out = String::new();121         line(&mut out, &["host", &clean(&self.arch)]);122         line(123             &mut out,124             &["driver", &self.driver.as_deref().map_or("-".into(), clean)],125         );126         line(127             &mut out,128             &["cuda", &self.cuda.as_deref().map_or("-".into(), clean)],129         );130         for soname in &self.sonames {131             line(&mut out, &["soname", &clean(soname)]);132         }133         for gpu in &self.gpus {134             let bytes = gpu.bytes.map_or("-".to_string(), |n| n.to_string());135             let free = gpu.free_bytes.map_or("-".to_string(), |n| n.to_string());136             let compute = gpu.compute.as_deref().map_or("-".into(), clean);137             line(138                 &mut out,139                 &[140                     "gpu",141                     &clean(&gpu.id),142                     &clean(&gpu.name),143                     &clean(&gpu.bus),144                     &bytes,145                     &free,146                     &compute,147                 ],148             );149         }150         out151     }152 153     /// Reads the record that [`Host::encode`] wrote.154     ///155     /// A missing `host` line or an unknown record shape is `None`. A numeric156     /// field that the probe did not measure is `None` on that device, not a157     /// reason to discard the rest of the host.158     pub fn decode(text: &str) -> Option<Host> {159         let mut arch = None;160         let mut driver = None;161         let mut cuda = None;162         let mut gpus = Vec::new();163         let mut sonames = BTreeSet::new();164         for line in text.lines() {165             let fields: Vec<&str> = line.split('\t').collect();166             match fields.first().copied()? {167                 "host" if fields.len() == 2 => arch = Some(fields[1].to_string()),168                 "driver" if fields.len() == 2 => {169                     driver = (fields[1] != "-").then(|| fields[1].to_string());170                 }171                 "cuda" if fields.len() == 2 => {172                     cuda = (fields[1] != "-").then(|| fields[1].to_string());173                 }174                 "soname" if fields.len() == 2 => {175                     sonames.insert(fields[1].to_string());176                 }177                 "gpu" if fields.len() == 7 => {178                     gpus.push(Gpu {179                         id: fields[1].to_string(),180                         name: fields[2].to_string(),181                         bus: fields[3].to_string(),182                         bytes: number(fields[4]),183                         free_bytes: number(fields[5]),184                         compute: (fields[6] != "-").then(|| fields[6].to_string()),185                     });186                 }187                 _ => return None,188             }189         }190         Some(Host {191             arch: arch?,192             driver,193             cuda,194             gpus,195             sonames,196         })197     }198 199     /// Whether a shared object with this name and at least this major version200     /// is on the machine.201     ///202     /// A `requires` entry is `name` or `name>=major`. The version is the major203     /// number in the soname: `libcudnn.so.9` is `cudnn` at 9.204     pub fn has_library(&self, requires: &str) -> bool {205         let (name, wanted) = match requires.split_once(">=") {206             Some((name, major)) => (name, major.parse::<u32>().ok()),207             None => (requires, None),208         };209         self.sonames.iter().any(|soname| {210             let Some((base, major)) = soname_version(soname) else {211                 return false;212             };213             base == name && wanted.is_none_or(|wanted| major >= wanted)214         })215     }216 }217 218 /// Appends one tab-separated record.219 fn line(out: &mut String, fields: &[&str]) {220     for (index, field) in fields.iter().enumerate() {221         if index > 0 {222             out.push('\t');223         }224         out.push_str(field);225     }226     out.push('\n');227 }228 229 /// A field cannot carry the record separators.230 fn clean(text: &str) -> String {231     text.replace(['\t', '\n', '\r'], " ")232 }233 234 /// A decimal field, where `-` means that the probe did not report it.235 fn number(text: &str) -> Option<u64> {236     if text == "-" { None } else { text.parse().ok() }237 }238 239 /// One kibibyte. `/proc/<pid>/status` reports `VmRSS` in kB.240 const KIB: u64 = 1 << 10;241 242 /// Resident bytes of a process, from `VmRSS` in `/proc/<pid>/status`.243 ///244 /// The number is what the process holds in memory now, so a caller can compare245 /// it with a declaration. `None` means the process is gone or the field is246 /// absent; a zero would be a guess that the process holds nothing.247 pub fn process_bytes(pid: u32) -> Option<u64> {248     let text = std::fs::read_to_string(format!("/proc/{pid}/status")).ok()?;249     parse_rss(&text)250 }251 252 /// A process and every descendant that the kernel reports.253 ///254 /// A bound bundle is a launcher: its weight file is read by a child, not by the255 /// process that the core started. Measuring the launcher alone would find only256 /// a few hundred kilobytes, so a load check walks the tree. The order is257 /// depth-first and the root is first.258 pub fn process_tree(pid: u32) -> Vec<u32> {259     let mut seen = BTreeSet::new();260     let mut pending = vec![pid];261     let mut tree = Vec::new();262     while let Some(pid) = pending.pop() {263         if !seen.insert(pid) {264             continue;265         }266         tree.push(pid);267         // A child belongs to the thread that forked it. A test thread and an268         // HTTP worker both fork, so every task of the process must be read,269         // not only the main thread.270         let tasks = format!("/proc/{pid}/task");271         let Ok(tasks) = std::fs::read_dir(tasks) else {272             continue;273         };274         for task in tasks.filter_map(Result::ok) {275             let path = task.path().join("children");276             let Ok(text) = std::fs::read_to_string(path) else {277                 continue;278             };279             for child in text.split_whitespace() {280                 if let Ok(child) = child.parse::<u32>() {281                     pending.push(child);282                 }283             }284         }285     }286     tree287 }288 289 /// Resident bytes of a process tree.290 ///291 /// A child that exited between the walk and the read is skipped. `None` means292 /// no process in the tree could be measured, which is not the same as a tree293 /// that holds zero bytes.294 pub fn process_tree_bytes(pid: u32) -> Option<u64> {295     let mut any = false;296     let mut total = 0u64;297     for pid in process_tree(pid) {298         if let Some(bytes) = process_bytes(pid) {299             any = true;300             total = total.saturating_add(bytes);301         }302     }303     any.then_some(total)304 }305 306 /// Bytes that the kernel says a new process can use without swapping.307 ///308 /// `None` means the kernel did not answer. It is deliberately separate from a309 /// device probe: a model load asks this once, while a settle loop must not run310 /// the whole host probe.311 pub fn available_memory() -> Option<u64> {312     probe_system_memory().and_then(|memory| memory.free)313 }314 315 /// The free bytes of one device, without probing the rest of the machine.316 ///317 /// A settle loop asks this every fifty milliseconds. A full `Host::probe` runs318 /// three `nvidia-smi` queries, `vulkaninfo`, the AMD tree, and `ldconfig`; that319 /// cost belongs at startup, not in a wait for one card to free one allocation.320 /// The CPU and Metal share the kernel's available memory.321 pub fn device_free_bytes(device: &str) -> Option<u64> {322     let (backend, index) = device.split_once(':')?;323     let index = index.parse::<u32>().ok()?;324     match backend {325         "cuda" => nvidia_free(index),326         "rocm" => amd_free(index),327         // CPU and Metal share one unified memory. The kernel's available328         // number is the best free figure that either can report.329         "cpu" | "metal" => probe_system_memory().and_then(|memory| memory.free),330         _ => None,331     }332 }333 334 fn nvidia_free(index: u32) -> Option<u64> {335     let output = Command::new("nvidia-smi")336         .args([337             format!("--id={index}"),338             "--query-gpu=memory.free".to_string(),339             "--format=csv,noheader,nounits".to_string(),340         ])341         .output()342         .ok()?;343     if !output.status.success() {344         return None;345     }346     let text = String::from_utf8_lossy(&output.stdout);347     let line = text.lines().find(|line| !line.trim().is_empty())?;348     mib(line)349 }350 351 /// Bytes of one CUDA device that a process tree holds.352 ///353 /// A driver reports one row per process that holds memory on the selected354 /// device. The sum over the tree is what the load check compares with the355 /// declaration. `None` is a driver that did not answer; a successful query with356 /// no matching row is `Some(0)`, because the device has measured the tree and357 /// found no allocation. ROCm and Vulkan have no equivalent query here.358 pub fn process_vram_bytes(pids: &[u32], device: &str) -> Option<u64> {359     let index = cuda_index(device)?;360     let wanted: BTreeSet<u32> = pids.iter().copied().collect();361     let output = Command::new("nvidia-smi")362         .args([363             format!("--id={index}"),364             "--query-compute-apps=pid,used_memory".to_string(),365             "--format=csv,noheader,nounits".to_string(),366         ])367         .output()368         .ok()?;369     if !output.status.success() {370         return None;371     }372     Some(parse_compute_memory(373         &String::from_utf8_lossy(&output.stdout),374         &wanted,375     ))376 }377 378 /// `1234, 512` per line: process id and MiB on one device.379 fn parse_compute_memory(text: &str, wanted: &BTreeSet<u32>) -> u64 {380     let mut total = 0u64;381     for line in text.lines() {382         let mut fields = line.split(',');383         let pid = fields.next().and_then(|pid| pid.trim().parse::<u32>().ok());384         let mib = fields.next().and_then(mib);385         if let (Some(pid), Some(bytes)) = (pid, mib)386             && wanted.contains(&pid)387         {388             total = total.saturating_add(bytes);389         }390     }391     total392 }393 394 /// `cuda:0` is device index `0`.395 fn cuda_index(device: &str) -> Option<u32> {396     device.strip_prefix("cuda:")?.parse().ok()397 }398 399 /// The sysfs tree that names every DRM card.400 const AMD_DRM: &str = "/sys/class/drm";401 402 /// The vendor id of an AMD device in sysfs.403 const AMD_VENDOR: &str = "0x1002";404 405 /// Where the amdgpu module reports its version.406 const AMD_DRIVER: &str = "/sys/module/amdgpu/version";407 408 /// One mebibyte in bytes. `/proc/meminfo` counts KiB and sysfs VRAM counts409 /// bytes; the CPU device converts once, here.410 const MEMINFO_KIB: u64 = 1 << 10;411 412 /// The major, minor, and stepping parts of a gfx target version.413 const GFX_MAJOR: u64 = 10_000;414 const GFX_MINOR: u64 = 100;415 416 /// `VmRSS:\t  1234 kB`.417 fn parse_rss(text: &str) -> Option<u64> {418     let line = text.lines().find(|line| line.starts_with("VmRSS:"))?;419     let kib = line.split_whitespace().nth(1)?.parse::<u64>().ok()?;420     Some(kib * KIB)421 }422 423 /// `libcudnn.so.9` is `cudnn` at 9.424 fn soname_version(soname: &str) -> Option<(String, u32)> {425     let rest = soname.strip_prefix("lib")?;426     let (base, tail) = rest.split_once(".so")?;427     let major = match tail.strip_prefix('.') {428         Some(version) => version.split('.').next()?.parse().ok()?,429         // `libcuda.so` is unversioned. It names the library but cannot meet a430         // major-version floor, so it matches only the bare name.431         None if tail.is_empty() => 0,432         None => return None,433     };434     Some((base.to_string(), major))435 }436 437 /// Reads `/proc/driver/nvidia/version`.438 ///439 /// The line is `NVRM version: ...  <version>  ...`.440 fn probe_driver(path: &Path) -> Option<String> {441     let text = std::fs::read_to_string(path).ok()?;442     parse_driver(&text)443 }444 445 fn parse_driver(text: &str) -> Option<String> {446     let line = text447         .lines()448         .find(|line| line.starts_with("NVRM version:"))?;449     line.split_whitespace()450         .find(|word| word.chars().next().is_some_and(|c| c.is_ascii_digit()))451         .map(str::to_string)452 }453 454 /// Lists the devices under `/proc/driver/nvidia/gpus` and asks the driver for455 /// each one's memory.456 fn probe_gpus(gpus: &Path, dev: &Path) -> Vec<Gpu> {457     let mut buses: Vec<String> = match std::fs::read_dir(gpus) {458         Ok(read) => read459             .filter_map(Result::ok)460             .map(|item| item.file_name().to_string_lossy().into_owned())461             .collect(),462         Err(_) => Vec::new(),463     };464     buses.sort();465 466     let memory = probe_memory();467     let compute = probe_compute();468     let mut devices = Vec::with_capacity(buses.len());469     for (index, bus) in buses.iter().enumerate() {470         // A device without a node cannot be opened, so it cannot be granted.471         if !dev.join(format!("nvidia{index}")).exists() {472             continue;473         }474         let info = std::fs::read_to_string(gpus.join(bus).join("information")).unwrap_or_default();475         let name = info476             .lines()477             .find_map(|line| line.strip_prefix("Model:"))478             .map(|name| name.trim().to_string())479             .unwrap_or_default();480         let (bytes, free_bytes) = memory481             .get(index)482             .map_or((None, None), |memory| (memory.total, memory.free));483         devices.push(Gpu {484             id: format!("cuda:{index}"),485             name,486             bus: bus.clone(),487             bytes,488             free_bytes,489             compute: compute.get(index).cloned().flatten(),490         });491     }492     devices493 }494 495 /// The CPU, or the unified memory of an Apple machine, as one device.496 ///497 /// A model that runs on the CPU still needs a ledger capacity, and a bind names498 /// `cpu:0` like any other device. The total is the machine's own memory, not a499 /// declared number, because a declaration that disagrees with the kernel is500 /// worse than none.501 fn probe_cpu() -> Option<Gpu> {502     let memory = probe_system_memory()?;503     let total = memory.total?;504     Some(Gpu {505         id: "cpu:0".to_string(),506         name: "CPU".to_string(),507         bus: "cpu".to_string(),508         bytes: Some(total),509         free_bytes: memory.free.map(|free| free.min(total)),510         compute: None,511     })512 }513 514 /// Metal has one unified-memory device on an Apple machine.515 ///516 /// The backend is the same memory as `cpu:0`; the id lets a target name the517 /// APIs it was built for without pretending that a discrete card exists.518 #[cfg(target_os = "macos")]519 fn probe_metal() -> Vec<Gpu> {520     let Some(memory) = probe_system_memory() else {521         return Vec::new();522     };523     let Some(total) = memory.total else {524         return Vec::new();525     };526     vec![Gpu {527         id: "metal:0".to_string(),528         name: "Apple Metal".to_string(),529         bus: "unified".to_string(),530         bytes: Some(total),531         free_bytes: memory.free.map(|free| free.min(total)),532         compute: None,533     }]534 }535 536 #[cfg(not(target_os = "macos"))]537 fn probe_metal() -> Vec<Gpu> {538     Vec::new()539 }540 541 /// The total and free memory of the machine.542 #[derive(Clone, Copy, Default)]543 struct SystemMemory {544     total: Option<u64>,545     free: Option<u64>,546 }547 548 #[cfg(target_os = "linux")]549 fn probe_system_memory() -> Option<SystemMemory> {550     let text = std::fs::read_to_string("/proc/meminfo").ok()?;551     parse_meminfo(&text)552 }553 554 #[cfg(target_os = "macos")]555 fn probe_system_memory() -> Option<SystemMemory> {556     let output = Command::new("sysctl")557         .args(["-n", "hw.memsize"])558         .output()559         .ok()?;560     if !output.status.success() {561         return None;562     }563     let total = String::from_utf8_lossy(&output.stdout)564         .trim()565         .parse()566         .ok()?;567     Some(SystemMemory {568         total: Some(total),569         free: None,570     })571 }572 573 #[cfg(not(any(target_os = "linux", target_os = "macos")))]574 fn probe_system_memory() -> Option<SystemMemory> {575     None576 }577 578 /// `MemTotal`, `MemAvailable`, and `MemFree`, in kB.579 ///580 /// `MemAvailable` is the kernel's estimate of memory that a new process can use581 /// without swapping; `MemFree` is the fallback on an older kernel.582 fn parse_meminfo(text: &str) -> Option<SystemMemory> {583     let mut memory = SystemMemory::default();584     for line in text.lines() {585         let Some((key, rest)) = line.split_once(':') else {586             continue;587         };588         let Some(value) = rest589             .split_whitespace()590             .next()591             .and_then(|value| value.parse::<u64>().ok())592         else {593             continue;594         };595         let bytes = value.checked_mul(MEMINFO_KIB)?;596         match key.trim() {597             "MemTotal" => memory.total = Some(bytes),598             "MemAvailable" => memory.free = Some(bytes),599             "MemFree" if memory.free.is_none() => memory.free = Some(bytes),600             _ => {}601         }602     }603     if let (Some(total), Some(free)) = (memory.total, memory.free) {604         memory.free = Some(free.min(total));605     }606     Some(memory)607 }608 609 /// AMD devices, from the amdgpu sysfs nodes.610 ///611 /// The card's `device` directory is the hardware record: its vendor says612 /// `0x1002`, its VRAM files give the bytes, and its uevent gives the PCI slot.613 /// The probe does not trust a name from a driver that has no device node.614 fn probe_amd(drm: &Path) -> Vec<Gpu> {615     amd_cards(drm)616         .into_iter()617         .enumerate()618         .map(|(index, card)| {619             let device = card.join("device");620             let total = read_number(device.join("mem_info_vram_total"));621             let used = read_number(device.join("mem_info_vram_used"));622             let free_bytes = total623                 .zip(used)624                 .map(|(total, used)| total.saturating_sub(used));625             let name = read_trim(device.join("product_name"))626                 .unwrap_or_else(|| format!("AMD GPU {index}"));627             let bus = read_uevent_bus(device.join("uevent"))628                 .or_else(|| {629                     card.file_name()630                         .map(|name| name.to_string_lossy().into_owned())631                 })632                 .unwrap_or_else(|| format!("rocm:{index}"));633             let compute = read_number(device.join("gfx_target_version")).map(format_gfx);634             Gpu {635                 id: format!("rocm:{index}"),636                 name,637                 bus,638                 bytes: total,639                 free_bytes,640                 compute,641             }642         })643         .collect()644 }645 646 /// The AMD cards under a DRM tree, in card-number order.647 fn amd_cards(drm: &Path) -> Vec<PathBuf> {648     let Ok(entries) = std::fs::read_dir(drm) else {649         return Vec::new();650     };651     let mut cards: Vec<(u32, PathBuf)> = entries652         .filter_map(Result::ok)653         .filter_map(|entry| {654             let name = entry.file_name();655             let index = name.to_str()?.strip_prefix("card")?.parse::<u32>().ok()?;656             let path = entry.path();657             let vendor = read_trim(path.join("device/vendor"))?;658             (vendor == AMD_VENDOR).then_some((index, path))659         })660         .collect();661     cards.sort_by_key(|(index, _)| *index);662     cards.into_iter().map(|(_, path)| path).collect()663 }664 665 /// The free bytes of one AMD device, in the same index order as `probe_amd`.666 fn amd_free(index: u32) -> Option<u64> {667     let cards = amd_cards(Path::new(AMD_DRM));668     let card = cards.get(usize::try_from(index).ok()?)?;669     let device = card.join("device");670     let total = read_number(device.join("mem_info_vram_total"))?;671     let used = read_number(device.join("mem_info_vram_used"))?;672     Some(total.saturating_sub(used))673 }674 675 /// The fields compose into the `gfx` family name.676 fn format_gfx(version: u64) -> String {677     let major = version / GFX_MAJOR;678     let minor = (version / GFX_MINOR) % GFX_MINOR;679     let stepping = version % GFX_MINOR;680     // AMD writes a two-digit stepping as a letter: 10 is `a`. A stepping681     // above `z` stays decimal instead of becoming a punctuation mark.682     let stepping = u8::try_from(stepping)683         .ok()684         .and_then(|step| step.checked_sub(10))685         .and_then(|offset| b'a'.checked_add(offset))686         .filter(u8::is_ascii_lowercase)687         .map_or_else(688             || stepping.to_string(),689             |letter| char::from(letter).to_string(),690         );691     format!("gfx{major}{minor}{stepping}")692 }693 694 /// The version of the amdgpu module, when the machine has one.695 ///696 /// Some kernels append a package suffix to the module version. A version697 /// comparison needs the dotted number, not the package name.698 fn probe_amd_driver() -> Option<String> {699     let text = read_trim(PathBuf::from(AMD_DRIVER))?;700     let version: String = text701         .chars()702         .take_while(|c| c.is_ascii_digit() || *c == '.')703         .collect();704     (!version.is_empty()).then_some(version)705 }706 707 /// Vulkan devices, from `vulkaninfo --summary`.708 ///709 /// The summary has the device names but not the memory heaps. A card that CUDA710 /// or ROCm already measured lends its numbers to the Vulkan id; a software711 /// device that no other probe saw keeps `bytes: None` rather than a guess.712 fn probe_vulkan(known: &[Gpu]) -> Vec<Gpu> {713     let Ok(output) = Command::new("vulkaninfo").arg("--summary").output() else {714         return Vec::new();715     };716     if !output.status.success() {717         return Vec::new();718     }719     parse_vulkan_summary(&String::from_utf8_lossy(&output.stdout))720         .into_iter()721         .enumerate()722         .map(|(index, name)| {723             // The same physical card can appear once under CUDA or ROCm and724             // again under Vulkan. Copying the measured numbers from the first725             // probe does not invent anything, and it lets a Vulkan target check726             // its memory.727             let known = known728                 .iter()729                 .find(|gpu| gpu.name == name && matches!(gpu.backend(), "cuda" | "rocm"));730             Gpu {731                 id: format!("vulkan:{index}"),732                 name,733                 bus: known.map_or_else(|| format!("vulkan:{index}"), |gpu| gpu.bus.clone()),734                 bytes: known.and_then(|gpu| gpu.bytes),735                 free_bytes: known.and_then(|gpu| gpu.free_bytes),736                 compute: known.and_then(|gpu| gpu.compute.clone()),737             }738         })739         .collect()740 }741 742 /// `deviceName = Synthetic GPU` per physical device.743 fn parse_vulkan_summary(text: &str) -> Vec<String> {744     text.lines()745         .filter_map(|line| {746             let (key, value) = line.trim().split_once('=')?;747             if key.trim() != "deviceName" {748                 return None;749             }750             let name = value.trim().trim_matches('"');751             (!name.is_empty()).then(|| name.to_string())752         })753         .collect()754 }755 756 fn read_trim(path: PathBuf) -> Option<String> {757     let text = std::fs::read_to_string(path).ok()?;758     let text = text.trim();759     (!text.is_empty()).then(|| text.to_string())760 }761 762 fn read_number(path: PathBuf) -> Option<u64> {763     read_trim(path)?.parse().ok()764 }765 766 /// `PCI_SLOT_NAME=0000:05:00.0` in a DRM device uevent.767 fn read_uevent_bus(path: PathBuf) -> Option<String> {768     read_trim(path)?769         .lines()770         .find_map(|line| line.strip_prefix("PCI_SLOT_NAME=").map(str::to_string))771 }772 773 /// One mebibyte. `nvidia-smi` prints MiB, and the ledger counts bytes.774 const MIB: u64 = 1 << 20;775 776 /// The memory of one device as `nvidia-smi` reports it.777 #[derive(Clone, Copy, Default)]778 struct Memory {779     total: Option<u64>,780     free: Option<u64>,781 }782 783 /// Asks `nvidia-smi` for the total and free memory of each device, in index784 /// order.785 ///786 /// It is the only interface that a driver offers for these numbers. Total and787 /// free come from one query because a second query per probe would read two788 /// different moments and could report free bytes above the total that it just789 /// read.790 fn probe_memory() -> Vec<Memory> {791     let output = std::process::Command::new("nvidia-smi")792         .args([793             "--query-gpu=memory.total,memory.free",794             "--format=csv,noheader,nounits",795         ])796         .output();797     let Ok(output) = output else {798         return Vec::new();799     };800     if !output.status.success() {801         return Vec::new();802     }803     parse_memory(&String::from_utf8_lossy(&output.stdout))804 }805 806 /// Two MiB counts per line, from `nvidia-smi`.807 fn parse_memory(text: &str) -> Vec<Memory> {808     text.lines()809         .filter(|line| !line.trim().is_empty())810         .map(|line| {811             let mut fields = line.split(',');812             let total = fields.next().and_then(mib);813             let free = fields.next().and_then(mib).map(|free| match total {814                 Some(total) => free.min(total),815                 None => free,816             });817             Memory { total, free }818         })819         .collect()820 }821 822 fn mib(text: &str) -> Option<u64> {823     text.trim().parse::<u64>().ok().map(|mib| mib * MIB)824 }825 826 /// The CUDA version in the `nvidia-smi` header.827 ///828 /// The header is the only place that the driver prints the runtime version, and829 /// it is not part of a `--query-gpu` reply. A second call is the whole cost of830 /// knowing whether a bundle built for one CUDA release can run here.831 fn probe_cuda() -> Option<String> {832     let output = std::process::Command::new("nvidia-smi").output().ok()?;833     if !output.status.success() {834         return None;835     }836     parse_cuda(&String::from_utf8_lossy(&output.stdout))837 }838 839 /// The `nvidia-smi` header names the driver and the CUDA version.840 /// or the newer `CUDA UMD Version: 13.4` spelling.841 fn parse_cuda(text: &str) -> Option<String> {842     for label in ["CUDA Version:", "CUDA UMD Version:"] {843         let Some(line) = text.lines().find(|line| line.contains(label)) else {844             continue;845         };846         let (_, tail) = line.split_once(label)?;847         let version = tail.split_whitespace().next()?;848         return Some(version.trim_end_matches('|').to_string());849     }850     None851 }852 853 /// Asks `nvidia-smi` for the compute capability of each device, in index order.854 fn probe_compute() -> Vec<Option<String>> {855     let output = std::process::Command::new("nvidia-smi")856         .args(["--query-gpu=compute_cap", "--format=csv,noheader,nounits"])857         .output();858     let Ok(output) = output else {859         return Vec::new();860     };861     if !output.status.success() {862         return Vec::new();863     }864     parse_compute(&String::from_utf8_lossy(&output.stdout))865 }866 867 /// A dotted capability per line becomes an `sm` name; `0.0` is `sm00`.868 fn parse_compute(text: &str) -> Vec<Option<String>> {869     text.lines()870         .filter(|line| !line.trim().is_empty())871         .map(|line| {872             let text = line.trim();873             let digits: String = text.chars().filter(|c| c.is_ascii_digit()).collect();874             if digits.is_empty() {875                 None876             } else {877                 Some(format!("sm{digits}"))878             }879         })880         .collect()881 }882 883 /// The sonames that `ldconfig` lists.884 fn probe_sonames() -> BTreeSet<String> {885     let output = std::process::Command::new("ldconfig").arg("-p").output();886     let Ok(output) = output else {887         return BTreeSet::new();888     };889     parse_sonames(&String::from_utf8_lossy(&output.stdout))890 }891 892 /// `libcudnn.so.9 (libc6,x86-64) => /usr/lib/libcudnn.so.9`.893 fn parse_sonames(text: &str) -> BTreeSet<String> {894     text.lines()895         .filter_map(|line| line.split_whitespace().next())896         .filter(|name| name.starts_with("lib") && name.contains(".so"))897         .map(str::to_string)898         .collect()899 }900 901 #[cfg(test)]902 mod tests {903     use super::*;904 905     #[test]906     fn the_driver_line_gives_the_version() {907         let text = "NVRM version: NVIDIA UNIX Open Kernel Module for x86_64  0.0.0  Release Build  (builder@example)\nGCC version:  gcc version 16.2.1\n";908         assert_eq!(parse_driver(text).as_deref(), Some("0.0.0"));909         assert_eq!(parse_driver("nothing here"), None);910     }911 912     #[test]913     fn memory_is_a_total_and_a_free_number_per_device() {914         let memory = parse_memory("2048, 1024\n4096, 4096\n");915         assert_eq!(memory.len(), 2);916         assert_eq!(memory[0].total, Some(2048 * MIB));917         assert_eq!(memory[0].free, Some(1024 * MIB));918         assert_eq!(memory[1].total, Some(4096 * MIB));919         assert_eq!(memory[1].free, Some(4096 * MIB));920         // `nvidia-smi` prints `[N/A]` for a number that it cannot read.921         let memory = parse_memory("[N/A], [N/A]\n2048, 1024\n");922         assert_eq!(memory[0].total, None);923         assert_eq!(memory[0].free, None);924         assert_eq!(memory[1].total, Some(2048 * MIB));925         // A free number above the total is a driver read of two moments; the926         // total is the ceiling that the ledger honours.927         let memory = parse_memory("100, 200\n");928         assert_eq!(memory[0].free, Some(100 * MIB));929         assert!(parse_memory("").is_empty());930     }931 932     #[test]933     fn rss_reads_a_status_line() {934         assert_eq!(935             parse_rss("Name:\tsh\nVmRSS:\t   1234 kB\n"),936             Some(1234 * KIB)937         );938         assert_eq!(parse_rss("Name:\tsh\n"), None);939         assert_eq!(parse_rss("VmRSS:\tnot a number\n"), None);940     }941 942     #[test]943     fn the_current_process_holds_at_least_the_bytes_it_allocated() {944         // A page of touched bytes is resident, so the allocation must be945         // visible against whatever else this test binary holds.946         let bytes = vec![1u8; 8 * 1024 * 1024];947         let measured = process_bytes(std::process::id()).expect("this process has an RSS");948         assert!(949             measured >= bytes.len() as u64,950             "{measured} < {}",951             bytes.len()952         );953         std::hint::black_box(&bytes);954     }955 956     #[test]957     fn a_soname_is_a_library_name_and_a_major_version() {958         assert_eq!(soname_version("libcudnn.so.9"), Some(("cudnn".into(), 9)));959         assert_eq!(960             soname_version("libcudart.so.12"),961             Some(("cudart".into(), 12))962         );963         assert_eq!(soname_version("libc.so.6"), Some(("c".into(), 6)));964         assert_eq!(soname_version("libcuda.so"), Some(("cuda".into(), 0)));965         assert_eq!(soname_version("ld-linux-x86-64.so.2"), None);966         assert_eq!(soname_version("/usr/lib/libc.so.6"), None);967     }968 969     #[test]970     fn meminfo_gives_total_and_the_best_free_number() {971         let text = "MemTotal:       32768 kB\nMemFree:         1024 kB\nMemAvailable:    2048 kB\n";972         let memory = parse_meminfo(text).expect("a meminfo");973         assert_eq!(memory.total, Some(32768 * MEMINFO_KIB));974         assert_eq!(memory.free, Some(2048 * MEMINFO_KIB));975 976         let old = "MemTotal: 1024 kB\nMemFree: 512 kB\n";977         assert_eq!(978             parse_meminfo(old).and_then(|memory| memory.free),979             Some(512 * MEMINFO_KIB)980         );981         assert_eq!(parse_meminfo("nothing").and_then(|m| m.total), None);982     }983 984     #[test]985     fn a_gfx_target_version_reads_as_its_family_name() {986         assert_eq!(format_gfx(0), "gfx000");987         assert_eq!(format_gfx(100), "gfx010");988         assert_eq!(format_gfx(10), "gfx00a");989         assert_eq!(format_gfx(36), "gfx0036");990     }991 992     #[test]993     fn a_vulkan_summary_keeps_one_name_per_device() {994         let text = "Devices:\n========\nGPU0:\n    deviceName = Synthetic GPU\nGPU1:\n    deviceName = llvmpipe (LLVM 18.1, 256 bits)\n";995         assert_eq!(996             parse_vulkan_summary(text),997             vec![998                 "Synthetic GPU".to_string(),999                 "llvmpipe (LLVM 18.1, 256 bits)".to_string()1000             ]1001         );1002         assert!(parse_vulkan_summary("no devices").is_empty());1003     }1004 1005     #[test]1006     fn an_amd_card_is_read_from_its_sysfs_node() {1007         let root = std::env::temp_dir().join(format!("inf3r-amd-{}", std::process::id()));1008         let _ = std::fs::remove_dir_all(&root);1009         let device = root.join("card0/device");1010         std::fs::create_dir_all(&device).expect("a card directory");1011         std::fs::write(device.join("vendor"), "0x1002\n").expect("a vendor");1012         std::fs::write(device.join("mem_info_vram_total"), "17163091968\n").expect("a total");1013         std::fs::write(device.join("mem_info_vram_used"), "4294967296\n").expect("a used");1014         std::fs::write(device.join("product_name"), "Synthetic GPU\n").expect("a name");1015         std::fs::write(device.join("gfx_target_version"), "0\n").expect("a gfx version");1016         std::fs::write(device.join("uevent"), "PCI_SLOT_NAME=0000:0a:00.0\n").expect("a bus");1017         let intel = root.join("card1/device");1018         std::fs::create_dir_all(&intel).expect("an intel card");1019         std::fs::write(intel.join("vendor"), "0x8086\n").expect("an intel vendor");1020 1021         let devices = probe_amd(&root);1022         assert_eq!(devices.len(), 1);1023         assert_eq!(devices[0].id, "rocm:0");1024         assert_eq!(devices[0].backend(), "rocm");1025         assert_eq!(devices[0].name, "Synthetic GPU");1026         assert_eq!(devices[0].bus, "0000:0a:00.0");1027         assert_eq!(devices[0].bytes, Some(17_163_091_968));1028         assert_eq!(devices[0].free_bytes, Some(17_163_091_968 - 4_294_967_296));1029         assert_eq!(devices[0].compute.as_deref(), Some("gfx000"));1030 1031         let _ = std::fs::remove_dir_all(&root);1032         assert!(probe_amd(Path::new("/does/not/exist")).is_empty());1033     }1034 1035     #[test]1036     fn a_ldconfig_line_keeps_its_first_word() {1037         let text = "\tlibcudnn.so.9 (libc6,x86-64) => /usr/lib/libcudnn.so.9\n\tlibc.so.6 (libc6,x86-64) => /usr/lib/libc.so.6\n";1038         let names = parse_sonames(text);1039         assert!(names.contains("libcudnn.so.9"));1040         assert!(names.contains("libc.so.6"));1041         assert_eq!(names.len(), 2);1042     }1043 1044     #[test]1045     fn the_header_gives_the_cuda_version() {1046         let text = "+-----------------------------------------------------------------------------+\n| NVIDIA-SMI 0.0.0   Driver Version: 0.0.0   CUDA Version: 13.0     |\n";1047         assert_eq!(parse_cuda(text).as_deref(), Some("13.0"));1048         let text = "+-----------------------------------------------------------------------------+\n| NVIDIA-SMI 0.0.0   KMD Version: 0.0.0   CUDA UMD Version: 13.4  |\n";1049         assert_eq!(parse_cuda(text).as_deref(), Some("13.4"));1050         assert_eq!(parse_cuda("no header"), None);1051     }1052 1053     #[test]1054     fn a_compute_capability_loses_its_dot() {1055         assert_eq!(1056             parse_compute("0.0\n0.1\n[N/A]\n"),1057             vec![Some("sm00".to_string()), Some("sm01".to_string()), None]1058         );1059     }1060 }