use crate::DeviceLocation;
use crate::error::Result;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum BackendId {
Cpu,
Cuda,
Vulkan,
Metal,
}
impl BackendId {
pub fn as_str(self) -> &'static str {
match self {
BackendId::Cpu => "cpu",
BackendId::Cuda => "cuda",
BackendId::Vulkan => "vulkan",
BackendId::Metal => "metal",
}
}
}
impl std::fmt::Display for BackendId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct DeviceDescriptor {
pub backend: BackendId,
pub device_index: u32,
pub hardware_sku: String,
pub vendor_id: u32,
pub device_id: u32,
pub compute_capability: Option<(u32, u32)>,
pub subgroup_width: Option<u32>,
pub driver_version: String,
pub total_memory_bytes: u64,
pub location: DeviceLocation,
}
impl DeviceDescriptor {
pub fn equivalence_key(&self) -> EquivalenceKey {
EquivalenceKey {
backend: self.backend,
vendor_id: self.vendor_id,
device_id: self.device_id,
compute_capability: self.compute_capability,
driver_version: self.driver_version.clone(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct EquivalenceKey {
pub backend: BackendId,
pub vendor_id: u32,
pub device_id: u32,
pub compute_capability: Option<(u32, u32)>,
pub driver_version: String,
}
pub trait BackendProbe {
fn enumerate_devices() -> Result<Vec<DeviceDescriptor>>;
}
impl DeviceLocation {
pub fn backend(self) -> BackendId {
match self {
DeviceLocation::Cpu => BackendId::Cpu,
DeviceLocation::Cuda { .. } => BackendId::Cuda,
DeviceLocation::Vulkan { .. } => BackendId::Vulkan,
DeviceLocation::Metal { .. } => BackendId::Metal,
}
}
}
impl BackendId {
pub fn default_location(self) -> DeviceLocation {
match self {
BackendId::Cpu => DeviceLocation::Cpu,
BackendId::Cuda => DeviceLocation::Cuda { gpu_id: 0 },
BackendId::Vulkan => DeviceLocation::Vulkan { gpu_id: 0 },
BackendId::Metal => DeviceLocation::Metal { gpu_id: 0 },
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct PciAddress {
pub domain: u32,
pub bus: u32,
pub device: u32,
pub function: Option<u32>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct DeviceIdentity {
pub uuid: Option<[u8; 16]>,
pub pci: Option<PciAddress>,
}
impl DeviceIdentity {
pub fn usable_uuid(&self) -> Option<[u8; 16]> {
self.uuid.filter(|u| u.iter().any(|b| *b != 0))
}
pub fn same_physical_device(&self, other: &DeviceIdentity) -> bool {
if let (Some(a), Some(b)) = (self.usable_uuid(), other.usable_uuid()) {
return a == b;
}
match (self.pci, other.pci) {
(Some(a), Some(b)) => {
a.domain == b.domain
&& a.bus == b.bus
&& a.device == b.device
&& match (a.function, b.function) {
(Some(x), Some(y)) => x == y,
_ => true,
}
}
_ => false,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum IdentityResolveError {
NoMatch,
Ambiguous(Vec<usize>),
}
pub fn resolve_identity_ordinal(
wanted: &DeviceIdentity,
enumerated: &[DeviceIdentity],
) -> std::result::Result<usize, IdentityResolveError> {
let hits: Vec<usize> = enumerated
.iter()
.enumerate()
.filter(|(_, id)| wanted.same_physical_device(id))
.map(|(i, _)| i)
.collect();
match hits.as_slice() {
[] => Err(IdentityResolveError::NoMatch),
[one] => Ok(*one),
_ => Err(IdentityResolveError::Ambiguous(hits)),
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum IdentityParseError {
Empty,
BadUuid,
ZeroUuid,
BadPci,
}
impl std::fmt::Display for IdentityParseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Empty => "empty device selector",
Self::BadUuid => {
"not a device UUID (want 8-4-4-4-12 hex digits, optional `GPU-` prefix)"
}
Self::ZeroUuid => "an all-zero UUID names no device",
Self::BadPci => "not a PCI address (want [domain:]bus:device[.function], hex)",
})
}
}
impl std::error::Error for IdentityParseError {}
impl std::str::FromStr for DeviceIdentity {
type Err = IdentityParseError;
fn from_str(text: &str) -> std::result::Result<Self, Self::Err> {
let t = text.trim();
if t.is_empty() {
return Err(IdentityParseError::Empty);
}
let bare = t
.strip_prefix("GPU-")
.or_else(|| t.strip_prefix("gpu-"))
.or_else(|| t.strip_prefix("MIG-"))
.unwrap_or(t);
if bare.contains(':') {
return parse_pci(bare).map(|pci| DeviceIdentity {
uuid: None,
pci: Some(pci),
});
}
let hex: String = bare.chars().filter(|c| *c != '-').collect();
if hex.len() != 32 || !hex.chars().all(|c| c.is_ascii_hexdigit()) {
return Err(IdentityParseError::BadUuid);
}
let mut uuid = [0u8; 16];
for (i, byte) in uuid.iter_mut().enumerate() {
*byte = u8::from_str_radix(&hex[2 * i..2 * i + 2], 16)
.map_err(|_| IdentityParseError::BadUuid)?;
}
if uuid.iter().all(|b| *b == 0) {
return Err(IdentityParseError::ZeroUuid);
}
Ok(DeviceIdentity {
uuid: Some(uuid),
pci: None,
})
}
}
fn parse_pci(text: &str) -> std::result::Result<PciAddress, IdentityParseError> {
let hex = |s: &str, max_digits: usize| -> std::result::Result<u32, IdentityParseError> {
if s.is_empty() || s.len() > max_digits || !s.chars().all(|c| c.is_ascii_hexdigit()) {
return Err(IdentityParseError::BadPci);
}
u32::from_str_radix(s, 16).map_err(|_| IdentityParseError::BadPci)
};
let parts: Vec<&str> = text.split(':').collect();
let (domain, bus, tail) = match parts.as_slice() {
[bus, tail] => (0, hex(bus, 2)?, *tail),
[domain, bus, tail] => (hex(domain, 4)?, hex(bus, 2)?, *tail),
_ => return Err(IdentityParseError::BadPci),
};
let (device, function) = match tail.split_once('.') {
Some((d, f)) => (hex(d, 2)?, Some(hex(f, 1)?)),
None => (hex(tail, 2)?, None),
};
if device > 0x1f || function.is_some_and(|f| f > 7) {
return Err(IdentityParseError::BadPci);
}
Ok(PciAddress {
domain,
bus,
device,
function,
})
}
pub fn identity_from_env(var: &str) -> std::result::Result<Option<DeviceIdentity>, String> {
identity_from_value(var, std::env::var(var).ok().as_deref())
}
pub fn identity_from_value(
var: &str,
value: Option<&str>,
) -> std::result::Result<Option<DeviceIdentity>, String> {
match value {
Some(v) if !v.trim().is_empty() => v
.parse::<DeviceIdentity>()
.map(Some)
.map_err(|e| format!("{var}={v:?}: {e}")),
_ => Ok(None),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn res_ident(uuid_byte: u8, bus: u32) -> DeviceIdentity {
DeviceIdentity {
uuid: Some([uuid_byte; 16]),
pci: Some(PciAddress {
domain: 0,
bus,
device: 0,
function: None,
}),
}
}
#[test]
fn resolver_follows_the_device_across_both_enumeration_orders() {
let nv = res_ident(0x11, 1);
let amd = res_ident(0x22, 6);
let amd_first = [amd, nv];
let nv_first = [nv, amd];
assert_eq!(resolve_identity_ordinal(&nv, &amd_first), Ok(1));
assert_eq!(resolve_identity_ordinal(&nv, &nv_first), Ok(0));
assert_eq!(resolve_identity_ordinal(&amd, &amd_first), Ok(0));
assert_eq!(resolve_identity_ordinal(&amd, &nv_first), Ok(1));
}
#[test]
fn resolver_declines_unknown_absent_and_ambiguous() {
let nv = res_ident(0x11, 1);
let amd = res_ident(0x22, 6);
assert_eq!(
resolve_identity_ordinal(&nv, &[amd]),
Err(IdentityResolveError::NoMatch)
);
assert_eq!(
resolve_identity_ordinal(&nv, &[]),
Err(IdentityResolveError::NoMatch)
);
let none = DeviceIdentity {
uuid: None,
pci: None,
};
assert_eq!(
resolve_identity_ordinal(&none, &[none]),
Err(IdentityResolveError::NoMatch)
);
let z = |bus| DeviceIdentity {
uuid: Some([0; 16]),
pci: Some(PciAddress {
domain: 0,
bus,
device: 0,
function: None,
}),
};
assert_eq!(resolve_identity_ordinal(&z(1), &[z(6), z(1)]), Ok(1));
assert_eq!(
resolve_identity_ordinal(&nv, &[nv, amd, nv]),
Err(IdentityResolveError::Ambiguous(vec![0, 2]))
);
}
#[test]
fn backend_id_as_str_is_stable() {
assert_eq!(BackendId::Cpu.as_str(), "cpu");
assert_eq!(BackendId::Cuda.as_str(), "cuda");
assert_eq!(BackendId::Vulkan.as_str(), "vulkan");
assert_eq!(BackendId::Metal.as_str(), "metal");
}
#[test]
fn equivalence_key_collapses_identical_cuda_devices() {
let make = |idx: u32| DeviceDescriptor {
backend: BackendId::Cuda,
device_index: idx,
hardware_sku: "NVIDIA GeForce RTX 4090".to_string(),
vendor_id: 0x10DE,
device_id: 0x2684,
compute_capability: Some((8, 9)),
subgroup_width: Some(32), driver_version: "550.54.14".to_string(),
total_memory_bytes: 25_769_803_776,
location: DeviceLocation::Cuda {
gpu_id: idx as usize,
},
};
let a = make(0);
let b = make(1);
assert_eq!(a.equivalence_key(), b.equivalence_key());
assert_ne!(a, b);
}
#[test]
fn equivalence_key_splits_same_silicon_across_backends() {
let cuda = DeviceDescriptor {
backend: BackendId::Cuda,
device_index: 0,
hardware_sku: "NVIDIA GeForce RTX 4090".to_string(),
vendor_id: 0x10DE,
device_id: 0x2684,
compute_capability: Some((8, 9)),
subgroup_width: Some(32),
driver_version: "550.54.14".to_string(),
total_memory_bytes: 25_769_803_776,
location: DeviceLocation::Cuda { gpu_id: 0 },
};
let vulkan = DeviceDescriptor {
backend: BackendId::Vulkan,
device_index: 0,
hardware_sku: "NVIDIA GeForce RTX 4090".to_string(),
vendor_id: 0x10DE,
device_id: 0x2684,
compute_capability: None, subgroup_width: Some(32),
driver_version: "550.54.14".to_string(),
total_memory_bytes: 25_769_803_776,
location: DeviceLocation::Cpu, };
assert_ne!(cuda.equivalence_key(), vulkan.equivalence_key());
}
#[test]
fn equivalence_key_splits_on_driver_version() {
let base = DeviceDescriptor {
backend: BackendId::Cuda,
device_index: 0,
hardware_sku: "X".to_string(),
vendor_id: 1,
device_id: 2,
compute_capability: Some((8, 9)),
subgroup_width: Some(32),
driver_version: "550".to_string(),
total_memory_bytes: 0,
location: DeviceLocation::Cuda { gpu_id: 0 },
};
let newer = DeviceDescriptor {
driver_version: "560".to_string(),
..base.clone()
};
assert_ne!(base.equivalence_key(), newer.equivalence_key());
}
#[test]
fn equivalence_key_ignores_subgroup_width() {
let base = DeviceDescriptor {
backend: BackendId::Vulkan,
device_index: 0,
hardware_sku: "X".to_string(),
vendor_id: 1,
device_id: 2,
compute_capability: None,
subgroup_width: None,
driver_version: "550".to_string(),
total_memory_bytes: 0,
location: DeviceLocation::Vulkan { gpu_id: 0 },
};
let with_width = DeviceDescriptor {
subgroup_width: Some(64),
..base.clone()
};
assert_ne!(base, with_width);
assert_eq!(base.equivalence_key(), with_width.equivalence_key());
}
#[test]
fn location_to_backend_ignores_the_ordinal() {
assert_eq!(DeviceLocation::Cpu.backend(), BackendId::Cpu);
for gpu_id in [0usize, 1, 7] {
assert_eq!(DeviceLocation::Cuda { gpu_id }.backend(), BackendId::Cuda);
assert_eq!(
DeviceLocation::Vulkan { gpu_id }.backend(),
BackendId::Vulkan
);
assert_eq!(DeviceLocation::Metal { gpu_id }.backend(), BackendId::Metal);
}
}
#[test]
fn default_location_round_trips_for_every_backend() {
for b in [
BackendId::Cpu,
BackendId::Cuda,
BackendId::Vulkan,
BackendId::Metal,
] {
assert_eq!(b.default_location().backend(), b, "{b:?}");
}
assert_eq!(
BackendId::Cuda.default_location(),
DeviceLocation::Cuda { gpu_id: 0 }
);
assert_eq!(BackendId::Cpu.default_location(), DeviceLocation::Cpu);
}
fn ident(uuid: Option<u8>, pci: Option<(u32, u32, u32, Option<u32>)>) -> DeviceIdentity {
DeviceIdentity {
uuid: uuid.map(|b| [b; 16]),
pci: pci.map(|(domain, bus, device, function)| PciAddress {
domain,
bus,
device,
function,
}),
}
}
#[test]
fn identity_uuid_decides_when_both_sides_have_one() {
let a = ident(Some(1), Some((0, 1, 0, None)));
assert!(a.same_physical_device(&ident(Some(1), Some((0, 9, 9, None)))));
assert!(!a.same_physical_device(&ident(Some(2), Some((0, 1, 0, None)))));
}
#[test]
fn identity_zero_uuid_is_absent_so_pci_decides() {
let zero = DeviceIdentity {
uuid: Some([0; 16]),
pci: Some(PciAddress {
domain: 0,
bus: 3,
device: 0,
function: Some(0),
}),
};
let other_zero_other_bus = DeviceIdentity {
uuid: Some([0; 16]),
pci: Some(PciAddress {
domain: 0,
bus: 4,
device: 0,
function: Some(0),
}),
};
assert!(!zero.same_physical_device(&other_zero_other_bus));
assert!(zero.same_physical_device(&zero));
}
#[test]
fn identity_pci_fallback_and_unknown() {
let cuda = ident(None, Some((0, 1, 0, None)));
assert!(cuda.same_physical_device(&ident(None, Some((0, 1, 0, Some(0))))));
assert!(!cuda.same_physical_device(&ident(None, Some((0, 2, 0, Some(0))))));
assert!(
!ident(Some(1), Some((0, 1, 0, Some(1))))
.same_physical_device(&ident(None, Some((0, 1, 0, Some(0)))))
);
assert!(!ident(None, None).same_physical_device(&ident(None, None)));
}
const NV: &str = "05c56c06-f951-3d45-5c8a-c76bbcb1deaa";
#[test]
fn selector_parses_uuid_in_every_written_form() {
let want: DeviceIdentity = NV.parse().unwrap();
assert_eq!(want.uuid.unwrap()[0], 0x05);
assert_eq!(want.uuid.unwrap()[15], 0xaa);
assert_eq!(want.pci, None);
assert_eq!(format!("GPU-{NV}").parse::<DeviceIdentity>(), Ok(want));
assert_eq!(NV.replace('-', "").parse::<DeviceIdentity>(), Ok(want));
assert_eq!(
format!(" {}\n", NV.to_uppercase()).parse::<DeviceIdentity>(),
Ok(want)
);
}
#[test]
fn selector_parses_pci_addresses() {
let p = |s: &str| s.parse::<DeviceIdentity>().unwrap().pci.unwrap();
let a = p("01:00.0");
assert_eq!((a.domain, a.bus, a.device, a.function), (0, 1, 0, Some(0)));
let b = p("0000:0a:1f.7");
assert_eq!(
(b.domain, b.bus, b.device, b.function),
(0, 0x0a, 0x1f, Some(7))
);
let c = p("0001:81:00");
assert_eq!((c.domain, c.bus, c.device, c.function), (1, 0x81, 0, None));
assert_eq!("01:00.0".parse::<DeviceIdentity>().unwrap().uuid, None);
}
#[test]
fn selector_refuses_what_is_not_a_device() {
use IdentityParseError::*;
let e = |s: &str| s.parse::<DeviceIdentity>().unwrap_err();
assert_eq!(e(""), Empty);
assert_eq!(e(" "), Empty);
assert_eq!(e("0"), BadUuid);
assert_eq!(e("zzzzzzzz-f951-3d45-5c8a-c76bbcb1deaa"), BadUuid);
assert_eq!(e(&NV[..35]), BadUuid);
assert_eq!(e("00000000-0000-0000-0000-000000000000"), ZeroUuid);
assert_eq!(e("01:00.8"), BadPci); assert_eq!(e("01:20.0"), BadPci); assert_eq!(e("01:"), BadPci);
assert_eq!(e("1:2:3:4"), BadPci);
assert_eq!(e("012:00.0"), BadPci); }
#[test]
fn selector_resolves_against_an_enumeration_in_either_order() {
let nv: DeviceIdentity = NV.parse().unwrap();
let other: DeviceIdentity = "11111111-2222-3333-4444-555555555555".parse().unwrap();
assert_eq!(resolve_identity_ordinal(&nv, &[nv, other]), Ok(0));
assert_eq!(resolve_identity_ordinal(&nv, &[other, nv]), Ok(1));
let gpu = |bus| DeviceIdentity {
uuid: None,
pci: Some(PciAddress {
domain: 0,
bus,
device: 0,
function: None,
}),
};
let want: DeviceIdentity = "0000:03:00.0".parse().unwrap();
assert_eq!(resolve_identity_ordinal(&want, &[gpu(1), gpu(3)]), Ok(1));
assert_eq!(
resolve_identity_ordinal(&want, &[gpu(1), gpu(2)]),
Err(IdentityResolveError::NoMatch)
);
}
#[test]
fn env_selector_is_unset_empty_good_or_a_named_error() {
let var = "FUEL_CUDA_DEVICE";
assert_eq!(identity_from_value(var, None), Ok(None));
assert_eq!(identity_from_value(var, Some(" ")), Ok(None));
assert_eq!(
identity_from_value(var, Some(NV)),
Ok(Some(NV.parse().unwrap()))
);
let err = identity_from_value(var, Some("not-a-gpu")).unwrap_err();
assert!(
err.contains(var) && err.contains("not a device UUID"),
"{err}"
);
}
}