Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
220 changes: 216 additions & 4 deletions crates/sbm_parser/src/inference.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
//! the weights' own format ([`vllm_memory_gib`]).

use serde::{Deserialize, Serialize};
use serde_json::{Deserializer, Map, Value};

/// An inference engine.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
Expand Down Expand Up @@ -250,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
Expand All @@ -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<u64> = 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<Gpu> = Vec::new();
let mut drm_intel = false;
let mut nvidia_runtime = false;
for line in out.lines() {
Expand Down Expand Up @@ -309,14 +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" => rocm_gpus = parse_rocm_smi(value),
_ => {}
}
}
hw.nvidia_containers = nvidia_runtime;
hw.rocm_devices &= hw.dri;
for vram in drm_amd {
hw.gpus.push(Gpu { vendor: "amd".into(), name: "AMD GPU".into(), memory_mib: (vram > 0).then_some(vram), compute: None });
}
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 });
}
Expand All @@ -336,6 +339,141 @@ fn parse_compute(s: &str) -> Option<u32> {
Some(major.parse::<u32>().ok()? * 10 + minor.parse::<u32>().ok()?)
}

/// Parses `rocm-smi --showproductname --showmeminfo vram --json` (`rocm_smi.py`),
/// where each `card<N>` holds flat string fields such as `"Card Series"` (or
/// `"Card series"`) and `"VRAM Total Memory (B)"`.
fn parse_rocm_smi(value: &str) -> Vec<Gpu> {
// `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::<Value>().next() else {
return Vec::new();
};
let mut cards: Vec<(u32, &Map<String, Value>)> = map
.iter()
.filter_map(|(k, v)| Some((k.strip_prefix("card")?.parse::<u32>().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<String, Value>, keys: &[&str]| -> Option<String> {
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::<u64>().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<Gpu>, drm_amd: Vec<u64>) -> Vec<Gpu> {
let mut drm_slots: Vec<Option<u64>> = 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

Expand Down Expand Up @@ -1071,6 +1209,80 @@ 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() {
// 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",
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(49152), compute: None },
Gpu { vendor: "amd".into(), name: "AMD Instinct MI300X".into(), memory_mib: Some(196608), compute: None },
]
);
}

#[test]
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",
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,
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]
fn use_cases_are_checked() {
let hw = nvidia(16384, 75, true);
Expand Down
Loading