From 79e85dcf05c8a89d90d5cf9be7f4f321497e1a82 Mon Sep 17 00:00:00 2001 From: pwu2775-dev Date: Thu, 3 Dec 2026 22:08:54 +0800 Subject: [PATCH 1/2] fix: inference: parse the rocm-smi probe the probe already ran MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit probe_command has asked every machine with rocm-smi for its cards — product names and VRAM, JSON, every probe — and parse_probe had no "rocm" arm, so the line was dropped on the floor: a real command's cost on each probe, and nothing to show for it. An iGPU or a container whose sysfs carries no mem_info_vram_total is exactly where rocm-smi is the only source: the DRM probe saw the card as vendor 0x1002 with a zero read, and said "AMD GPU" with no memory. The answer is read now: each card's gpu_type/market_name and its VRAM unit-converted to MiB, replacing the DRM probe's blind slot (a card with no figure) rather than sitting beside it, and appended as-is when there were more cards than blind slots. Where sysfs already answered with a real figure, rocm-smi's output is left unread — the two would have listed the same card twice. --- crates/sbm_parser/src/inference.rs | 91 ++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) diff --git a/crates/sbm_parser/src/inference.rs b/crates/sbm_parser/src/inference.rs index 01c9eb695f..91265bb22e 100644 --- a/crates/sbm_parser/src/inference.rs +++ b/crates/sbm_parser/src/inference.rs @@ -17,6 +17,7 @@ //! the weights' own format ([`vllm_memory_gib`]). use serde::{Deserialize, Serialize}; +use serde_json::Value; /// An inference engine. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] @@ -271,6 +272,9 @@ pub fn parse_probe(out: &str) -> Hardware { let mut hw = Hardware::default(); let mut apple_chip = None; let mut drm_amd: Vec = Vec::new(); + // `rocm-smi`'s answer, when its output was read: real card names and VRAM + // figures for the cards the sysfs DRM probe could only see as a vendor id. + let mut rocm_gpus: Vec = Vec::new(); let mut drm_intel = false; let mut nvidia_runtime = false; for line in out.lines() { @@ -309,14 +313,63 @@ pub fn parse_probe(out: &str) -> Hardware { "python" => hw.python = true, "ollama" => hw.ollama = true, "nvidia_runtime" | "nvidia_cdi" => nvidia_runtime = true, + "rocm" if !drm_amd.iter().any(|vram| *vram > 0) => { + // rocm-smi's `--json` output, keyed by card: `{"card0": {"gpu_type": + // ..., "vram": {"total": ..., "unit": ...}}, ...}`. Only consulted + // when the sysfs DRM probe found no AMD card with a real VRAM + // figure — where it can read one, `mem_info_vram_total` already + // answered, and the two would list the same card twice. + let Ok(Value::Object(cards)) = serde_json::from_str::(value) else { + continue; + }; + for card in cards.values() { + let name = card + .get("gpu_type") + .or_else(|| card.get("market_name")) + .and_then(|v| v.as_str()) + .unwrap_or("AMD GPU"); + let vram = card.get("vram"); + let total = vram + .and_then(|v| v.get("total")) + .and_then(|v| v.as_u64()) + .unwrap_or(0); + let unit = vram + .and_then(|v| v.get("unit")) + .and_then(|v| v.as_str()) + .unwrap_or("MB"); + let mib = match unit.to_ascii_uppercase().as_str() { + "GB" => total * 1024, + "KB" => total / 1024, + "B" => total / 1024 / 1024, + _ => total, + }; + rocm_gpus.push(Gpu { + vendor: "amd".into(), + name: name.to_string(), + memory_mib: (mib > 0).then_some(mib), + compute: None, + }); + } + } _ => {} } } hw.nvidia_containers = nvidia_runtime; hw.rocm_devices &= hw.dri; for vram in drm_amd { + // A card the sysfs probe saw but could not read a VRAM figure for + // (`mem_info_vram_total` absent — some iGPUs, some containers): what + // rocm-smi said about it is strictly better than an unnamed entry + // carrying nothing, so the two are one card, said once. + if vram == 0 && !rocm_gpus.is_empty() { + hw.gpus.push(rocm_gpus.remove(0)); + continue; + } hw.gpus.push(Gpu { vendor: "amd".into(), name: "AMD GPU".into(), memory_mib: (vram > 0).then_some(vram), compute: None }); } + // More rocm cards than the DRM probe had blind slots for: they are real + // cards too, and this is the only place their names and memory appear. + hw.gpus.extend(rocm_gpus); if drm_intel { hw.gpus.push(Gpu { vendor: "intel".into(), name: "Intel GPU".into(), memory_mib: None, compute: None }); } @@ -1071,6 +1124,44 @@ mod tests { assert!(f.iter().any(|f| f.engine == Engine::Vllm && f.blocked.as_deref() == Some("needsNvidia"))); } + #[test] + fn rocm_smi_answers_where_the_drm_probe_cannot() { + // An iGPU or a container whose sysfs carries no `mem_info_vram_total`: + // the DRM line reads zero, and rocm-smi is the only source left. Its + // output was run on every probe and then dropped on the floor — + // `parse_probe` had no `rocm` arm. The blind DRM slot is replaced by + // the card rocm-smi actually saw, by name and memory. + let out = concat!( + "os=Linux\narch=x86_64\nmemory_kib=16000000\n", + "drm=0x1002 0\nkfd=1\ndri=1\n", + r#"rocm={"card0":{"gpu_type":"AMD Radeon 780M","vram":{"total":16384,"unit":"MB"}},"card1":{"market_name":"Radeon Pro W7900","vram":{"total":48,"unit":"GB"}}}"#, + "\n", + ); + let hw = parse_probe(out); + assert_eq!( + hw.gpus, + vec![ + Gpu { vendor: "amd".into(), name: "AMD Radeon 780M".into(), memory_mib: Some(16384), compute: None }, + Gpu { vendor: "amd".into(), name: "Radeon Pro W7900".into(), memory_mib: Some(48 * 1024), compute: None }, + ] + ); + } + + #[test] + fn rocm_smi_does_not_duplicate_a_card_the_drm_probe_found() { + // Where sysfs already answered with a real VRAM figure, rocm-smi's + // output is the same card a second time and is left out. + let out = concat!( + "os=Linux\narch=x86_64\n", + "drm=0x1002 17163091968\nkfd=1\ndri=1\n", + r#"rocm={"card0":{"gpu_type":"AMD Radeon 780M","vram":{"total":16384,"unit":"MB"}}}"#, + "\n", + ); + let hw = parse_probe(out); + assert_eq!(hw.gpus.len(), 1); + assert_eq!(hw.gpus[0].memory_mib, Some(16368)); + } + #[test] fn use_cases_are_checked() { let hw = nvidia(16384, 75, true); From 3c15bec70eb83756a822ab0e4ba8f7050dd40369 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?lollipopkit=F0=9F=8F=B3=EF=B8=8F=E2=80=8D=E2=9A=A7?= =?UTF-8?q?=EF=B8=8F?= <10864310+lollipopkit@users.noreply.github.com> Date: Fri, 4 Dec 2026 01:18:31 +0800 Subject: [PATCH 2/2] fix: parse real rocm-smi JSON schema and reconcile AMD DRM slots after probe --- crates/sbm_parser/src/inference.rs | 263 +++++++++++++++++++++-------- 1 file changed, 192 insertions(+), 71 deletions(-) diff --git a/crates/sbm_parser/src/inference.rs b/crates/sbm_parser/src/inference.rs index 91265bb22e..6a5debc64d 100644 --- a/crates/sbm_parser/src/inference.rs +++ b/crates/sbm_parser/src/inference.rs @@ -17,7 +17,7 @@ //! the weights' own format ([`vllm_memory_gib`]). use serde::{Deserialize, Serialize}; -use serde_json::Value; +use serde_json::{Deserializer, Map, Value}; /// An inference engine. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] @@ -251,7 +251,7 @@ fi if command -v rocm-smi >/dev/null 2>&1; then rocm-smi --showproductname --showmeminfo vram --json 2>/dev/null | tr -d '\n' | sed 's/^/rocm=/'; echo fi -for d in /sys/class/drm/card[0-9]*/device; do +for d in /sys/class/drm/card[0-9]/device /sys/class/drm/card[0-9][0-9]/device /sys/class/drm/card[0-9][0-9][0-9]/device; do [ -r "$d/vendor" ] || continue echo "drm=$(cat "$d/vendor") $(cat "$d/mem_info_vram_total" 2>/dev/null || echo 0)" done @@ -313,63 +313,13 @@ pub fn parse_probe(out: &str) -> Hardware { "python" => hw.python = true, "ollama" => hw.ollama = true, "nvidia_runtime" | "nvidia_cdi" => nvidia_runtime = true, - "rocm" if !drm_amd.iter().any(|vram| *vram > 0) => { - // rocm-smi's `--json` output, keyed by card: `{"card0": {"gpu_type": - // ..., "vram": {"total": ..., "unit": ...}}, ...}`. Only consulted - // when the sysfs DRM probe found no AMD card with a real VRAM - // figure — where it can read one, `mem_info_vram_total` already - // answered, and the two would list the same card twice. - let Ok(Value::Object(cards)) = serde_json::from_str::(value) else { - continue; - }; - for card in cards.values() { - let name = card - .get("gpu_type") - .or_else(|| card.get("market_name")) - .and_then(|v| v.as_str()) - .unwrap_or("AMD GPU"); - let vram = card.get("vram"); - let total = vram - .and_then(|v| v.get("total")) - .and_then(|v| v.as_u64()) - .unwrap_or(0); - let unit = vram - .and_then(|v| v.get("unit")) - .and_then(|v| v.as_str()) - .unwrap_or("MB"); - let mib = match unit.to_ascii_uppercase().as_str() { - "GB" => total * 1024, - "KB" => total / 1024, - "B" => total / 1024 / 1024, - _ => total, - }; - rocm_gpus.push(Gpu { - vendor: "amd".into(), - name: name.to_string(), - memory_mib: (mib > 0).then_some(mib), - compute: None, - }); - } - } + "rocm" => rocm_gpus = parse_rocm_smi(value), _ => {} } } hw.nvidia_containers = nvidia_runtime; hw.rocm_devices &= hw.dri; - for vram in drm_amd { - // A card the sysfs probe saw but could not read a VRAM figure for - // (`mem_info_vram_total` absent — some iGPUs, some containers): what - // rocm-smi said about it is strictly better than an unnamed entry - // carrying nothing, so the two are one card, said once. - if vram == 0 && !rocm_gpus.is_empty() { - hw.gpus.push(rocm_gpus.remove(0)); - continue; - } - hw.gpus.push(Gpu { vendor: "amd".into(), name: "AMD GPU".into(), memory_mib: (vram > 0).then_some(vram), compute: None }); - } - // More rocm cards than the DRM probe had blind slots for: they are real - // cards too, and this is the only place their names and memory appear. - hw.gpus.extend(rocm_gpus); + hw.gpus.extend(reconcile_amd_gpus(rocm_gpus, drm_amd)); if drm_intel { hw.gpus.push(Gpu { vendor: "intel".into(), name: "Intel GPU".into(), memory_mib: None, compute: None }); } @@ -389,6 +339,141 @@ fn parse_compute(s: &str) -> Option { Some(major.parse::().ok()? * 10 + minor.parse::().ok()?) } +/// Parses `rocm-smi --showproductname --showmeminfo vram --json` (`rocm_smi.py`), +/// where each `card` holds flat string fields such as `"Card Series"` (or +/// `"Card series"`) and `"VRAM Total Memory (B)"`. +fn parse_rocm_smi(value: &str) -> Vec { + // `rocm_smi.py` may print `WARNING: ...` lines to stdout ahead of the JSON + // payload when a GPU is in runtime PM low-power state. + let Some(json) = value.find('{').map(|i| &value[i..]) else { + return Vec::new(); + }; + let Some(Ok(Value::Object(map))) = Deserializer::from_str(json).into_iter::().next() else { + return Vec::new(); + }; + let mut cards: Vec<(u32, &Map)> = map + .iter() + .filter_map(|(k, v)| Some((k.strip_prefix("card")?.parse::().ok()?, v.as_object()?))) + .collect(); + cards.sort_by_key(|(idx, _)| *idx); + + let is_hex_pci_id = |s: &str| { + s.strip_prefix("0x") + .or_else(|| s.strip_prefix("0X")) + .is_some_and(|hex| !hex.is_empty() && hex.chars().all(|c| c.is_ascii_hexdigit())) + }; + let pick_str = |obj: &Map, keys: &[&str]| -> Option { + keys.iter().find_map(|target| { + obj.iter() + .find(|(k, _)| k.eq_ignore_ascii_case(target)) + .and_then(|(_, v)| v.as_str()) + .map(str::trim) + .filter(|s| !s.is_empty() && !s.eq_ignore_ascii_case("n/a")) + .map(str::to_owned) + }) + }; + + let mut out = Vec::new(); + for (_, obj) in cards { + if obj.is_empty() || obj.keys().any(|k| k.starts_with("Incompatible device")) { + continue; + } + let mut confirmed_amd = false; + if let Some(vendor) = pick_str(obj, &["Card Vendor"]) { + let upper = vendor.to_ascii_uppercase(); + let is_amd = upper.contains("AMD") + || upper.contains("ADVANCED MICRO DEVICES") + || upper.contains("ATI") + || upper == "0X1002" + || upper == "1002"; + if !is_amd { + continue; + } + confirmed_amd = true; + } + // Without `pci.ids`, `rocm-smi` writes the raw hex PCI device ID into + // `Card Series`; skip bare hex IDs so the card falls back to a real + // name field or `"AMD GPU"`. + let raw_name = ["Card Series", "Market Name", "Device Name"] + .iter() + .find_map(|k| pick_str(obj, &[k]).filter(|s| !is_hex_pci_id(s))); + let bytes = obj + .iter() + .find(|(k, _)| k.eq_ignore_ascii_case("VRAM Total Memory (B)")) + .and_then(|(_, v)| v.as_u64().or_else(|| v.as_str()?.trim().parse::().ok())) + .unwrap_or(0); + let mib = bytes / 1024 / 1024; + if raw_name.is_none() && mib == 0 && !confirmed_amd { + continue; + } + out.push(Gpu { + vendor: "amd".into(), + name: raw_name.unwrap_or_else(|| "AMD GPU".into()), + memory_mib: (mib > 0).then_some(mib), + compute: None, + }); + } + out +} + +/// Merges `rocm-smi` cards with `/sys/class/drm` AMD VRAM readings without +/// duplicating cards when only a subset of AMD GPUs (e.g. dGPU beside an iGPU) +/// is reported by `rocm-smi`. +fn reconcile_amd_gpus(mut rocm_gpus: Vec, drm_amd: Vec) -> Vec { + let mut drm_slots: Vec> = drm_amd.into_iter().map(Some).collect(); + + // Pass 1a: exact VRAM matches first across all ROCm cards so an earlier + // approximate card cannot steal a later card's exact sysfs slot. + let mut matched = vec![false; rocm_gpus.len()]; + for (idx, gpu) in rocm_gpus.iter().enumerate() { + let Some(m) = gpu.memory_mib else { continue }; + if let Some(i) = drm_slots.iter().position(|s| *s == Some(m)) { + drm_slots[i] = None; + matched[idx] = true; + } + } + + // Pass 1b: remaining ROCm cards with known VRAM claim a blind (`0`) DRM + // slot first, then the first unclaimed slot. + for (idx, gpu) in rocm_gpus.iter().enumerate() { + if matched[idx] || gpu.memory_mib.is_none() { + continue; + } + let i = drm_slots + .iter() + .position(|s| *s == Some(0)) + .or_else(|| drm_slots.iter().position(Option::is_some)); + if let Some(i) = i { + drm_slots[i] = None; + } + } + + // Pass 2: ROCm cards without VRAM claim remaining DRM slots and inherit + // any non-zero sysfs VRAM reading. + for gpu in &mut rocm_gpus { + if gpu.memory_mib.is_some() { + continue; + } + if let Some(slot) = drm_slots.iter_mut().find(|s| s.is_some()) + && let Some(vram) = slot.take() + && vram > 0 + { + gpu.memory_mib = Some(vram); + } + } + + let mut out = rocm_gpus; + for vram in drm_slots.into_iter().flatten() { + out.push(Gpu { + vendor: "amd".into(), + name: "AMD GPU".into(), + memory_mib: (vram > 0).then_some(vram), + compute: None, + }); + } + out +} + // --------------------------------------------------------------------------- // llmfit @@ -1126,40 +1211,76 @@ mod tests { #[test] fn rocm_smi_answers_where_the_drm_probe_cannot() { - // An iGPU or a container whose sysfs carries no `mem_info_vram_total`: - // the DRM line reads zero, and rocm-smi is the only source left. Its - // output was run on every probe and then dropped on the floor — - // `parse_probe` had no `rocm` arm. The blind DRM slot is replaced by - // the card rocm-smi actually saw, by name and memory. + // Real `probe_command()` order (`rocm=` before `drm=`) and real + // `rocm_smi.py` `--showproductname --showmeminfo vram --json` keys, + // including a top-level `"system"` entry and `card10` numeric ordering. let out = concat!( "os=Linux\narch=x86_64\nmemory_kib=16000000\n", - "drm=0x1002 0\nkfd=1\ndri=1\n", - r#"rocm={"card0":{"gpu_type":"AMD Radeon 780M","vram":{"total":16384,"unit":"MB"}},"card1":{"market_name":"Radeon Pro W7900","vram":{"total":48,"unit":"GB"}}}"#, - "\n", + r#"rocm={"system":{"Driver version":"6.10.5"},"card0":{"Card Series":"AMD Radeon 780M","VRAM Total Memory (B)":"17179869184","Card Vendor":"Advanced Micro Devices, Inc. [AMD/ATI]"},"card2":{"Card series":"Radeon Pro W7900","VRAM Total Memory (B)":"51539607552"},"card10":{"Market Name":"AMD Instinct MI300X","VRAM Total Memory (B)":"206158430208"}}"#, + "\ndrm=0x1002 0\nkfd=1\ndri=1\n", ); let hw = parse_probe(out); assert_eq!( hw.gpus, vec![ Gpu { vendor: "amd".into(), name: "AMD Radeon 780M".into(), memory_mib: Some(16384), compute: None }, - Gpu { vendor: "amd".into(), name: "Radeon Pro W7900".into(), memory_mib: Some(48 * 1024), compute: None }, + Gpu { vendor: "amd".into(), name: "Radeon Pro W7900".into(), memory_mib: Some(49152), compute: None }, + Gpu { vendor: "amd".into(), name: "AMD Instinct MI300X".into(), memory_mib: Some(196608), compute: None }, ] ); } #[test] - fn rocm_smi_does_not_duplicate_a_card_the_drm_probe_found() { - // Where sysfs already answered with a real VRAM figure, rocm-smi's - // output is the same card a second time and is left out. + fn rocm_smi_merges_with_drm_in_probe_order_without_duplicating() { + // `probe_command()` prints `rocm=` before `drm=`, and on a hybrid host + // `rocm-smi` also emits an `"Incompatible device..."` entry for non-AMD + // DRM cards. The AMD card must appear once with its product name, and + // the Intel card must not become a second AMD entry. let out = concat!( "os=Linux\narch=x86_64\n", - "drm=0x1002 17163091968\nkfd=1\ndri=1\n", - r#"rocm={"card0":{"gpu_type":"AMD Radeon 780M","vram":{"total":16384,"unit":"MB"}}}"#, - "\n", + r#"rocm={"card0":{"Incompatible device.\nGPU[0]\t\t: Expected vendor name: Advanced Micro Devices, Inc. [AMD/ATI]\nGPU[0]\t\t: Actual vendor name":"Intel","VRAM Total Memory (B)":"N/A"},"card1":{"Card Series":"Radeon RX 7900 XT","Card Model":"0x744c","Card Vendor":"Advanced Micro Devices, Inc. [AMD/ATI]","VRAM Total Memory (B)":"21458059264","VRAM Total Used Memory (B)":"27856896"}}"#, + "\ndrm=0x8086 0\ndrm=0x1002 21458059264\nkfd=1\ndri=1\n", ); let hw = parse_probe(out); - assert_eq!(hw.gpus.len(), 1); - assert_eq!(hw.gpus[0].memory_mib, Some(16368)); + assert_eq!( + hw.gpus, + vec![ + Gpu { vendor: "amd".into(), name: "Radeon RX 7900 XT".into(), memory_mib: Some(20464), compute: None }, + Gpu { vendor: "intel".into(), name: "Intel GPU".into(), memory_mib: None, compute: None }, + ] + ); + } + + #[test] + fn rocm_smi_handles_igpu_plus_dgpu_warnings_and_missing_pci_ids() { + // Ryzen APU iGPU (512 MiB in sysfs, omitted by rocm-smi) + RX 7900 XTX + // (24560 MiB in both), with a leading low-power WARNING on stdout. + let out = concat!( + "os=Linux\narch=x86_64\n", + r#"rocm=WARNING: AMD GPU device(s) is/are in a low-power state. {"card1":{"Card Series":"Radeon RX 7900 XTX","Card Vendor":"Advanced Micro Devices, Inc. [AMD/ATI]","VRAM Total Memory (B)":"25753026560"}}"#, + "\ndrm=0x1002 536870912\ndrm=0x1002 25753026560\nkfd=1\ndri=1\n", + ); + let hw = parse_probe(out); + assert_eq!( + hw.gpus, + vec![ + Gpu { vendor: "amd".into(), name: "Radeon RX 7900 XTX".into(), memory_mib: Some(24560), compute: None }, + Gpu { vendor: "amd".into(), name: "AMD GPU".into(), memory_mib: Some(512), compute: None }, + ] + ); + + // Minimal container without `pci.ids`: vendor is `"0x1002"` and series + // is a raw hex PCI device ID `"0x744c"`. + let container_out = concat!( + "os=Linux\narch=x86_64\n", + r#"rocm={"card0":{"Card Series":"0x744c","Card Vendor":"0x1002","VRAM Total Memory (B)":"21458059264"},"card1":{"VRAM Total Memory (B)":"N/A"}}"#, + "\nkfd=1\ndri=1\n", + ); + let container_hw = parse_probe(container_out); + assert_eq!( + container_hw.gpus, + vec![Gpu { vendor: "amd".into(), name: "AMD GPU".into(), memory_mib: Some(20464), compute: None }] + ); } #[test]